dongyan8929 2018-01-11 14:04
浏览 111

下载excelize xlsx文件已损坏

I'm using Excelize library for generating xlsx documents. When I use It's Write(io.writer) func for saving xlsx to file, it works perfectly. But I need to generate and serve this file at web-server. I was trying this solution

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)
}

and after that i've got corrupted zip-file from web-server, but normal file saved in "/tmp/testfile.xlsx"

I've tried content-type as application/zip, application/octet-stream, application/vnd.* but no luck.

Can you help me? Thank you in advance.

PS: By serving i mean on-the-fly generation of file, sorry for any misunderstanding.

PS2: It seems I get an overhead of downloaded file (8085 bytes of original and 13000+ of downloaded) and I can't figure it out where this overhead is come in.

  • 写回答

1条回答 默认 最新

  • doureng6738 2018-01-11 14:16
    关注

    For serving a reader, you should consider http.ServeContent. It will handle the header, content range and so on for you. Change the line withio.Copy with http.ServeContent(w,r,"testfile.xlsx",time.Now(),t) and it shall work. Documents: https://golang.org/pkg/net/http/#ServeContent

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大