Skip to content

Commit

Permalink
spreadsheet: support inserting rows within a sheet
Browse files Browse the repository at this point in the history
  • Loading branch information
tbaliance committed Sep 28, 2018
1 parent ed84939 commit 3148419
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
Binary file not shown.
36 changes: 36 additions & 0 deletions _examples/spreadsheet/insert-rows/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright 2017 Baliance. All rights reserved.
package main

import (
"fmt"
"log"

"baliance.com/gooxml/spreadsheet"
)

func main() {
ss := spreadsheet.New()
// add a single sheet
sheet := ss.AddSheet()

// rows
for r := 0; r < 5; r++ {
row := sheet.AddRow()
// and cells
for c := 0; c < 5; c++ {
cell := row.AddCell()
cell.SetString(fmt.Sprintf("row %d cell %d", r, c))
}
}

// no insert some rows after row 2
for i := 0; i < 4; i++ {
sheet.InsertRow(2).AddCell().SetString(fmt.Sprintf("inserted at 2, iter %d", i))
}

if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}

ss.SaveToFile("insert-rows.xlsx")
}
24 changes: 24 additions & 0 deletions spreadsheet/sheet.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,30 @@ func (s Sheet) AddRow() Row {
return s.AddNumberedRow(maxRowID + 1)
}

// InsertRow inserts a new row into a spreadsheet at a particular row number. This
// row will now be the row number specified, and any rows after it will be renumbed.
func (s Sheet) InsertRow(rowNum int) Row {
rIdx := uint32(rowNum)

// Renumber every row after the row we're inserting
for _, r := range s.Rows() {
if r.x.RAttr != nil && *r.x.RAttr >= rIdx {
*r.x.RAttr++
// and we also need to recompute cell references
for _, c := range r.Cells() {
cref, err := reference.ParseCellReference(c.Reference())
if err != nil {
continue
}
cref.RowIdx++
c.x.RAttr = gooxml.String(cref.String())
}
}
}
// finally AddNumberedRow will add and re-sort rows
return s.AddNumberedRow(rIdx)
}

// Name returns the sheet name
func (s Sheet) Name() string {
return s.cts.NameAttr
Expand Down

0 comments on commit 3148419

Please sign in to comment.