golang 导出CSV文件

2023-03-07  本文已影响0人  Super淳语


func (c *cMapiReport) ExportXXXXX(r *ghttp.Request) {
    //内容先写入buffer缓存 
    buff :=  new(bytes.Buffer)

    //写入UTF-8 BOM,此处如果不写入就会导致写入的汉字乱码
    buff.WriteString("\xEF\xBB\xBF")

    csvWriter := csv.NewWriter(buff)
    //写入表头
    csvWriter.Write([]string{
       "XXID", "订单号", "发起时间", "接单时间", "XX时间", "错误信息", "耗时(秒)", "机器编号",
    })

    //写入内容
    for i := 0; i < len(output.Items); i++ {
       outputItem := output.Items[i]
       csvWriter.Write([]string{
       gconv.String(outputItem.Id),
       outputItem.OrderSn,
       outputItem.RequestTime.String(),
       outputItem.DispatchTime.String(),
       outputItem.CallbackTime.String(),
       outputItem.ErrMsg,
       outputItem.ManHour,
       outputItem.HostName,
      })
    }

    //将缓冲区数据写入
    csvWriter.Flush()

    //设置http表头为下载
    r.Response.Header().Set("Content-Type", "application/force-download")
    r.Response.Header().Set("Accept-Ranges", "bytes")
    r.Response.Header().Set("Content-Disposition", fmt.Sprintf(`attachment;filename=%s`, url.QueryEscape("XX详情导出"+req.StartDate+"&"+req.EndDate+".csv")))
    r.Response.Write(buff.Bytes())
}

上一篇下一篇

猜你喜欢

热点阅读