asp.net导出csv文件

.NET
359
0
0
2022-03-22
标签   ASP.NET
IList<OrgSendStatData> ObjList=(IList<OrgSendStatData>) Session["ObjList"];
       string csv = "业务,活动,部门,本机构汇总总数,本机构汇总成功数,本机构汇总失败数,本机构及子机构汇总总数,本机构及子机构汇总成功数,本机构及子机构汇总失败数\r\n";
       StringBuilder sb = new StringBuilder();
       foreach (OrgSendStatData m in ObjList)
       {
           sb.Append(GetOperName(m.OperationId).Replace(',',',') + ",");
           sb.Append(GetMarkName(m.OperationMark) + ",");
           sb.Append(GetOrgName(m.OrgId) + ",");
           sb.Append(m.SingleOrgTotalCount.ToString() + ",");
           sb.Append(m.SingleOrgSuccessCount.ToString() + ",");
           sb.Append(m.SingleOrgDefeatCount.ToString() + ",");
           sb.Append(m.AllOrgTotalCount.ToString() + ",");
           sb.Append(m.AllOrgSuccessCount.ToString() + ",");
           sb.Append(m.AllOrgDefeatCount.ToString() + ",");
           sb.Append("\r\n");
       }
       csv += sb.ToString();
       //下面将文本输出为csv个数,可用excel直接打开
       Response.Clear();
       Response.Buffer = true;
       Response.Charset = "gb2312";
       //下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
       //filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt .htm 
       Response.AppendHeader("Content-Disposition", "attachment;filename=\"OrgCount.csv\"");
       Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
       //Response.ContentType指定文件类型 可以为application/ms-excel application/ms-word application/ms-txt application/ms-html 或其他浏览器可直接支持文档 
       Response.ContentType = "application/ms-excel";
       this.EnableViewState = false;
       System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
       oStringWriter.Write(csv);
       oStringWriter.Flush();
       System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
       this.RenderControl(oHtmlTextWriter);
       //this 表示输出本页,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件 
       Response.Write(oStringWriter.ToString());
       Response.End();