refactor DeleteSheet for better readability (#1078)

Signed-off-by: Michael Wiesenbauer <michael.wiesenbauer@ambos.io>
Co-authored-by: Michael Wiesenbauer <michael.wiesenbauer@fau.de>
pull/2/head
Michael Wiesenbauer 3 years ago committed by GitHub
parent 4ca1b305fe
commit aa359f1c74
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -555,23 +555,13 @@ func (f *File) DeleteSheet(name string) {
wbRels := f.relsReader(f.getWorkbookRelsPath())
activeSheetName := f.GetSheetName(f.GetActiveSheetIndex())
deleteLocalSheetID := f.GetSheetIndex(name)
// Delete and adjust defined names
if wb.DefinedNames != nil {
for idx := 0; idx < len(wb.DefinedNames.DefinedName); idx++ {
dn := wb.DefinedNames.DefinedName[idx]
if dn.LocalSheetID != nil {
localSheetID := *dn.LocalSheetID
if localSheetID == deleteLocalSheetID {
wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName[:idx], wb.DefinedNames.DefinedName[idx+1:]...)
idx--
} else if localSheetID > deleteLocalSheetID {
wb.DefinedNames.DefinedName[idx].LocalSheetID = intPtr(*dn.LocalSheetID - 1)
}
}
}
}
deleteAndAdjustDefinedNames(wb, deleteLocalSheetID)
for idx, sheet := range wb.Sheets.Sheet {
if strings.EqualFold(sheet.Name, sheetName) {
if !strings.EqualFold(sheet.Name, sheetName) {
continue
}
wb.Sheets.Sheet = append(wb.Sheets.Sheet[:idx], wb.Sheets.Sheet[idx+1:]...)
var sheetXML, rels string
if wbRels != nil {
@ -593,10 +583,32 @@ func (f *File) DeleteSheet(name string) {
delete(f.xmlAttr, sheetXML)
f.SheetCount--
}
}
f.SetActiveSheet(f.GetSheetIndex(activeSheetName))
}
func deleteAndAdjustDefinedNames(wb *xlsxWorkbook, deleteLocalSheetID int) {
if wb == nil {
return
}
if wb.DefinedNames == nil {
return
}
for idx := 0; idx < len(wb.DefinedNames.DefinedName); idx++ {
dn := wb.DefinedNames.DefinedName[idx]
if dn.LocalSheetID != nil {
localSheetID := *dn.LocalSheetID
if localSheetID == deleteLocalSheetID {
wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName[:idx], wb.DefinedNames.DefinedName[idx+1:]...)
idx--
} else if localSheetID > deleteLocalSheetID {
wb.DefinedNames.DefinedName[idx].LocalSheetID = intPtr(*dn.LocalSheetID - 1)
}
}
}
}
// deleteSheetFromWorkbookRels provides a function to remove worksheet
// relationships by given relationships ID in the file workbook.xml.rels.
func (f *File) deleteSheetFromWorkbookRels(rID string) string {

Loading…
Cancel
Save