美文网首页
golang 导出CSV文件

golang 导出CSV文件

作者: Super淳语 | 来源:发表于2023-03-07 10:14 被阅读0次
    
    
    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())
    }
    
    

    相关文章

      网友评论

          本文标题:golang 导出CSV文件

          本文链接:https://www.haomeiwen.com/subject/xbnvldtx.html