下载excelize xlsx文件已损坏

时间:2018-01-11 14:04:31

标签: go webserver xlsx

我使用Excelize库生成xlsx文档。当我使用它的Write(io.writer) func将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)
}

之后我从网络服务器上获得了损坏的zip文件,但正常的文件保存在" /tmp/testfile.xlsx"

我已尝试将内容类型设为application/zipapplication/octet-streamapplication/vnd.*,但没有运气。

你能帮帮我吗?提前谢谢。

PS:通过服务我的意思是动态生成文件,对不起任何误解。

PS2:我似乎得到了下载文件的开销(8085字节的原始文件和13000+的下载文件),我无法弄清楚这个开销的来源。

1 个答案:

答案 0 :(得分:1)

为了服务读者,您应该考虑http.ServeContent。它将为您处理标题,内容范围等。 使用io.Copy更改http.ServeContent(w,r,"testfile.xlsx",time.Now(),t)行,它将起作用。 文件:https://golang.org/pkg/net/http/#ServeContent

相关问题