在 Google App Engine 上用 Go 语言打开由 tealeg xlsx 制作的 XLSX 文件时出错

Error when opening XLSX file made by tealeg xlsx in Go language on Google App Engine

我正在使用 https://github.com/tealeg/xlsx 生成 Go 语言的 xlsx 文件。该应用程序在 Google App Engine 上 运行。

var file *xlsx.File
var sheet *xlsx.Sheet
var row *xlsx.Row
var cell *xlsx.Cell
var err error

file = xlsx.NewFile()
sheet, err = file.AddSheet("TEST")
if err != nil {
  fmt.Printf(err.Error())
}
row = sheet.AddRow()
cell = row.AddCell()
cell.Value = "I am a cell!"

w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
w.Header().Add("Content-Disposition", "attachment; filename=Test.xlsx")
file.Write(w)
fmt.Fprint(w, nil)

变量w是http.ResponseWriter.

我已经测试了这段代码,浏览器成功下载了 xlsx 文件,我可以在 Linux 64 位上使用 LibreOffice 打开它。但是,当我尝试在 Windows 7 32 位上使用 Microsoft Excel 2010 打开文件时,它给了我以下错误消息:-

Excel found unreadable content in 'Test.xlsx'. Do you want to recover the contents of this workbook? If you trust the source of this workbook, click Yes.

单击“是”后,它会正确显示内容 "I am a cell!" 然后我单击“启用编辑”按钮,它给了我一条消息:-

Excel completed file level validation and repair. Some parts of this workbook may have been repaired or discarded.

如何通过使 Microsoft Excel 打开由 tealeg/xlsx 生成的 xlsx 文件而不显示任何错误消息来解决此问题?

你的最后一行完全没有必要,它破坏了 Excel 文件(XLSX 是一个 zip 存档):

fmt.Fprint(w, nil)

这将在您已经写入 Excel 文件的内容后将 "<nil>" 字符串的字节打印到网络响应中,我相信您只是意外地离开了那里。删除那个。

还有File.Write()returns和error,还要检查一下,例如:

if err = file.Write(w); err != nil {
    // Handle error, e.g. log it and send back an error response
}

如果错误仍然存​​在,则与 AppEngine 无关。我建议首先在本地尝试 Excel 生成,使用 File.Save() 将其保存到文件中,例如:

if err = file.Save("MyXLSXFile.xlsx"); err != nil {
    fmt.Println("Failed to save file:", err)
}
// If no error, try opening "MyXLSXFile.xlsx" on you computer.

另请注意图书馆主页的评论:

The support for writing XLSX files is currently extremely minimal. It will expand slowly, but in the meantime patches are welcome!