Skip to content

Commit

Permalink
Fix out of range panic when removing formula.
Browse files Browse the repository at this point in the history
Fix file corruption issue when deleting a sheet containing a formula.
  • Loading branch information
aplulu committed Apr 9, 2019
1 parent 4e7d93a commit 841ff4a
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 7 deletions.
22 changes: 16 additions & 6 deletions calcchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,12 @@ func (f *File) calcChainWriter() {

// deleteCalcChain provides a function to remove cell reference on the
// calculation chain.
func (f *File) deleteCalcChain(axis string) {
func (f *File) deleteCalcChain(index int, axis string) {
calc := f.calcChainReader()
if calc != nil {
for i, c := range calc.C {
if c.R == axis {
calc.C = append(calc.C[:i], calc.C[i+1:]...)
}
}
calc.C = xlsxCalcChainCollection(calc.C).Filter(func(c xlsxCalcChainC) bool {
return !((c.I == index && c.R == axis) || (c.I == index && axis == ""))
})
}
if len(calc.C) == 0 {
f.CalcChain = nil
Expand All @@ -53,3 +51,15 @@ func (f *File) deleteCalcChain(axis string) {
}
}
}

type xlsxCalcChainCollection []xlsxCalcChainC

func (c xlsxCalcChainCollection) Filter(fn func(v xlsxCalcChainC) bool) []xlsxCalcChainC {
results := make([]xlsxCalcChainC, 0)
for _, v := range c {
if fn(v) {
results = append(results, v)
}
}
return results
}
2 changes: 1 addition & 1 deletion cell.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ func (f *File) SetCellFormula(sheet, axis, formula string) error {
}
if formula == "" {
cellData.F = nil
f.deleteCalcChain(axis)
f.deleteCalcChain(f.GetSheetIndex(sheet), axis)
return err
}

Expand Down
1 change: 1 addition & 0 deletions sheet.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,7 @@ func (f *File) DeleteSheet(name string) {
rels := "xl/worksheets/_rels/sheet" + strconv.Itoa(v.SheetID) + ".xml.rels"
target := f.deleteSheetFromWorkbookRels(v.ID)
f.deleteSheetFromContentTypes(target)
f.deleteCalcChain(v.SheetID, "") // Delete CalcChain
delete(f.sheetMap, name)
delete(f.XLSX, sheet)
delete(f.XLSX, rels)
Expand Down

0 comments on commit 841ff4a

Please sign in to comment.