Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

excelize对已经存在的xlsx文件调用NewSheet()时会可能导致与打开的xlsx文件存在相同的sheetId,用Excel 2013打开时提示错误! #249

Closed
blueicesir opened this issue Jul 16, 2018 · 3 comments

Comments

@blueicesir
Copy link

用excelize打开存在的 xlsx文件(里面已经存在多个worksheet时),再次使用NewSheet函数增加新的工作表是,xl\workbook.xml原数据中可能会导致存在相同的sheetId=""数值。
例如,新增ICT_DT_SRC名称的worksheet之后,发现sheetId="14"的存在两个。Excel2013打开时提示错误。虽然可以自动修复。

@xuri
Copy link
Member

xuri commented Jul 16, 2018

Thanks for your issue. Please provide file attachments If you can.

@blueicesir
Copy link
Author

blueicesir commented Jul 17, 2018

// 代码为utf-8字符集
// 错误问题重现测试代码
package main

import (
"os"
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)

func main(){
// 这个文件在下面的测试文件中,是用Excel打开新建多个sheet之后删除之后再新建,达到模拟sheetid被占用的目的。
exist_xlsx:="C:\Temp\test.xlsx"
xlsx,err:=excelize.OpenFile(exist_xlsx)
if err!=nil{
fmt.Println(err)
os.Exit(0)
}

sheet_name:="新建sheet"
index:= xlsx.NewSheet(sheet_name)
fmt.Println(fmt.Sprintf("NEW SHEET ID=%d",index))

sheets_info:=xlsx.GetSheetMap()
for s := range sheets_info{
	fmt.Println(fmt.Sprintf("%d\t%s",s,sheets_info[s]))
}


xlsx.SetActiveSheet(index)
for i:=1; i<=10 ;i++ {
	xlsx.SetCellValue(sheet_name,fmt.Sprintf("A%d",i),i)
}
// 另存文件
xlsx.SaveAs("C:\\Temp\\test_bad.xlsx")

}

test.xlsx是用Excel 2013生成的合法文件,test_bad.xlsx是上述代码另存的文件。
test_bad.xlsx打开时报错。

sheetId="11" 出现两次。
<sheet name="新建sheet" sheetId="11"

test.xlsx
test_bad.xlsx

我的水平有限,但修改代码之后Excel打开没有报错了。
// FileName:sheet.go
// setWorkbook update workbook property of XLSX. Maximum 31 characters are
// allowed in sheet title.
// 通过枚举存在的工作表,查找到最大的SheetID,然后新增的时候SheetID+1的结果带入新生成的SheetID,防止workbook.xml的SheetID冲突。
// 请官方的大神最佳化代码。我是新手!
func (f *File) setWorkbook(name string, rid int) {
content := f.workbookReader()
max_sheetid:=0
for c:=range content.Sheets.Sheet{
tmp_sheetid,_:=strconv.Atoi(content.Sheets.Sheet[c].SheetID)
if max_sheetid<tmp_sheetid {
max_sheetid=tmp_sheetid
}
}
max_sheetid=max_sheetid+1
content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
Name: trimSheetName(name),
SheetID: strconv.Itoa(max_sheetid),
ID: "rId" + strconv.Itoa(rid),
})
}

@xuri
Copy link
Member

xuri commented Jul 17, 2018

I have fixed this issue. Please upgrade lib to the last version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants