我使用Excelize库来生成xlsx文档。当我使用它的Write(io.writer)函数将xlsx保存到文件时,它工作得很好。但是我需要在web服务器上生成并提供这个文件。我正在尝试这个解决方案
func GetConsolidatedReport(w http.ResponseWriter, r *http.Request) {
var reportFile *excelize.File
...
var b bytes.Buffer
writr := bufio.NewWriter(&b)
reportFile.SaveAs("/tmp/testfile.xlsx")
reportFile.Write(writr)
writr.Flush()
fileContents := b.Bytes()
fileSize := strconv.Itoa(len(fileContents))
w.Header().Set("Content-Disposition", "attachment; filename=report.xlsx")
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", fileSize)
t := bytes.NewReader(b.Bytes())
io.Copy(w, t)
}在那之后,我从web服务器得到了损坏的zip文件,但正常的文件保存在"/tmp/testfile.xlsx“中。
我尝试过application/zip、application/octet-stream、application/vnd.*等内容类型,但没有成功。
你能帮帮我吗?提前谢谢你。
PS:我所说的服务是指即时生成文件,抱歉有任何误解。
PS2:似乎我得到了一个下载文件的开销(8085字节的原始文件和下载的13000+ ),但我不知道这个开销是从哪里来的。
发布于 2018-01-11 22:16:47
为了服务读者,你应该考虑http.ServeContent。它将为您处理标题、内容范围等。用http.ServeContent(w,r,"testfile.xlsx",time.Now(),t)修改io.Copy的代码行,它就可以工作了。文档:https://golang.org/pkg/net/http/#ServeContent
发布于 2022-01-05 12:24:34
我使用*File.write应用程序接口,它可以工作:
package main
import (
"net/http"
"github.com/xuri/excelize/v2"
)
func main() {
s := http.Server{
Addr: ":8012",
}
http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
f := excelize.NewFile()
// Set value of a cell.
f.SetCellValue("Sheet1", "B2", 100)
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment; filename=example.xlsx")
w.Header().Set("Content-Transfer-Encoding", "binary")
f.Write(w)
})
s.ListenAndServe()
}https://stackoverflow.com/questions/48208908
复制相似问题