Browse Source

Get sheet names based on index

SheetID only seems to indicate the file name for the sheet.
Check the sheets list based on index instead. Reordering sheets
in Excel changes the order they appear in that list.

Fixes #457
Harris 6 years ago
parent
commit
faaaa52cb8
2 changed files with 27 additions and 9 deletions
  1. 6 9
      sheet.go
  2. 21 0
      sheet_test.go

+ 6 - 9
sheet.go

@@ -317,14 +317,11 @@ func (f *File) SetSheetName(oldName, newName string) {
 // string.
 func (f *File) GetSheetName(index int) string {
 	wb := f.workbookReader()
-	if wb != nil {
-		for _, sheet := range wb.Sheets.Sheet {
-			if sheet.SheetID == index {
-				return sheet.Name
-			}
-		}
+	realIdx := index - 1 // sheets are 1 based index, but we're checking against an array
+	if wb == nil || realIdx < 0 || realIdx >= len(wb.Sheets.Sheet) {
+		return ""
 	}
-	return ""
+	return wb.Sheets.Sheet[realIdx].Name
 }
 
 // GetSheetIndex provides a function to get worksheet index of XLSX by given
@@ -357,8 +354,8 @@ func (f *File) GetSheetMap() map[int]string {
 	wb := f.workbookReader()
 	sheetMap := map[int]string{}
 	if wb != nil {
-		for _, sheet := range wb.Sheets.Sheet {
-			sheetMap[sheet.SheetID] = sheet.Name
+		for i, sheet := range wb.Sheets.Sheet {
+			sheetMap[i+1] = sheet.Name
 		}
 	}
 	return sheetMap

+ 21 - 0
sheet_test.go

@@ -225,3 +225,24 @@ func TestUngroupSheets(t *testing.T) {
 	}
 	assert.NoError(t, f.UngroupSheets())
 }
+
+func TestGetSheetName(t *testing.T) {
+	f, _ := excelize.OpenFile(filepath.Join("test", "Book1.xlsx"))
+	assert.Equal(t, "Sheet1", f.GetSheetName(1))
+	assert.Equal(t, "Sheet2", f.GetSheetName(2))
+	assert.Equal(t, "", f.GetSheetName(0))
+	assert.Equal(t, "", f.GetSheetName(3))
+}
+
+func TestGetSheetMap(t *testing.T) {
+	expectedMap := map[int]string{
+		1: "Sheet1",
+		2: "Sheet2",
+	}
+	f, _ := excelize.OpenFile(filepath.Join("test", "Book1.xlsx"))
+	sheetMap := f.GetSheetMap()
+	for idx, name := range sheetMap {
+		assert.Equal(t, expectedMap[idx], name)
+	}
+	assert.Equal(t, len(sheetMap), 2)
+}