From c815e4b84b9b777c30d127f384b38105afa2640d Mon Sep 17 00:00:00 2001 From: yuemanxilou Date: Fri, 15 May 2020 14:03:02 +0800 Subject: [PATCH] avoid duplicate filter database in workbook defined name --- table.go | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/table.go b/table.go index ae47471f..5a0e46f8 100644 --- a/table.go +++ b/table.go @@ -281,28 +281,38 @@ func (f *File) AutoFilter(sheet, hcell, vcell, format string) error { formatSet, _ := parseAutoFilterSet(format) var cellStart, cellEnd string - cellStart, err = CoordinatesToCellName(hcol, hrow) - if err != nil { + if cellStart, err = CoordinatesToCellName(hcol, hrow); err != nil { return err } - cellEnd, err = CoordinatesToCellName(vcol, vrow) - if err != nil { + if cellEnd, err = CoordinatesToCellName(vcol, vrow); err != nil { return err } - ref := cellStart + ":" + cellEnd + ref, filterDB := cellStart+":"+cellEnd, "_xlnm._FilterDatabase" wb := f.workbookReader() + sheetID := f.GetSheetIndex(sheet) + filterRange := fmt.Sprintf("%s!%s", sheet, ref) d := xlsxDefinedName{ - Name: "_xlnm._FilterDatabase", + Name: filterDB, Hidden: true, - LocalSheetID: intPtr(f.GetSheetIndex(sheet)), - Data: fmt.Sprintf("%s!%s", sheet, ref), + LocalSheetID: intPtr(sheetID), + Data: filterRange, } - if wb.DefinedNames != nil { - wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName, d) - } else { + if wb.DefinedNames == nil { wb.DefinedNames = &xlsxDefinedNames{ DefinedName: []xlsxDefinedName{d}, } + } else { + var definedNameExists bool + for idx := range wb.DefinedNames.DefinedName { + definedName := wb.DefinedNames.DefinedName[idx] + if definedName.Name == filterDB && *definedName.LocalSheetID == sheetID && definedName.Hidden { + wb.DefinedNames.DefinedName[idx].Data = filterRange + definedNameExists = true + } + } + if !definedNameExists { + wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName, d) + } } refRange := vcol - hcol return f.autoFilter(sheet, ref, refRange, hcol, formatSet)