From 9c3a5eb9835e7b52350da3a2910b603c88f90bdc Mon Sep 17 00:00:00 2001 From: Liron Levin Date: Sat, 7 Jan 2023 07:17:00 +0200 Subject: [PATCH] Add missing error checks in `getSheetMap` to fix panic(#1437) Unit tests updated --- excelize.go | 4 +++- excelize_test.go | 5 ++++- sheet.go | 14 ++++++++++---- sheet_test.go | 6 ++++++ 4 files changed, 23 insertions(+), 6 deletions(-) diff --git a/excelize.go b/excelize.go index 3acdb43c0f..b41cd00a23 100644 --- a/excelize.go +++ b/excelize.go @@ -179,7 +179,9 @@ func OpenReader(r io.Reader, opts ...Options) (*File, error) { if f.CalcChain, err = f.calcChainReader(); err != nil { return f, err } - f.sheetMap = f.getSheetMap() + if f.sheetMap, err = f.getSheetMap(); err != nil { + return f, err + } if f.Styles, err = f.stylesReader(); err != nil { return f, err } diff --git a/excelize_test.go b/excelize_test.go index 47d83a855f..a1857fe4dd 100644 --- a/excelize_test.go +++ b/excelize_test.go @@ -250,7 +250,10 @@ func TestOpenReader(t *testing.T) { assert.NoError(t, zw.Close()) return buf } - for _, defaultXMLPath := range []string{defaultXMLPathCalcChain, defaultXMLPathStyles} { + for _, defaultXMLPath := range []string{ + defaultXMLPathCalcChain, + defaultXMLPathStyles, + defaultXMLPathWorkbookRels} { _, err = OpenReader(preset(defaultXMLPath)) assert.EqualError(t, err, "XML syntax error on line 1: invalid UTF-8") } diff --git a/sheet.go b/sheet.go index 15e19c5b1f..a4be16a523 100644 --- a/sheet.go +++ b/sheet.go @@ -454,10 +454,16 @@ func (f *File) GetSheetList() (list []string) { // getSheetMap provides a function to get worksheet name and XML file path map // of the spreadsheet. -func (f *File) getSheetMap() map[string]string { +func (f *File) getSheetMap() (map[string]string, error) { maps := map[string]string{} - wb, _ := f.workbookReader() - rels, _ := f.relsReader(f.getWorkbookRelsPath()) + wb, err := f.workbookReader() + if err != nil { + return nil, err + } + rels, err := f.relsReader(f.getWorkbookRelsPath()) + if err != nil { + return nil, err + } for _, v := range wb.Sheets.Sheet { for _, rel := range rels.Relationships { if rel.ID == v.ID { @@ -471,7 +477,7 @@ func (f *File) getSheetMap() map[string]string { } } } - return maps + return maps, nil } // getSheetXMLPath provides a function to get XML file path by given sheet diff --git a/sheet_test.go b/sheet_test.go index 09b6155422..f809fe8f99 100644 --- a/sheet_test.go +++ b/sheet_test.go @@ -378,6 +378,12 @@ func TestGetSheetMap(t *testing.T) { } assert.Equal(t, len(sheetMap), 2) assert.NoError(t, f.Close()) + + f = NewFile() + f.WorkBook = nil + f.Pkg.Store(defaultXMLPathWorkbook, MacintoshCyrillicCharset) + _, err = f.getSheetMap() + assert.EqualError(t, err, "XML syntax error on line 1: invalid UTF-8") } func TestSetActiveSheet(t *testing.T) {