版权声明:本文为博主原创文章,未经博主允许不得转载。
1:导出数据为Excel文件在开发项目时比较常见的一种需求 。以前对于数据量较小的情况使用 Microsoft.Office.Interop.Excel.Workbooks相关类,编写起来也比较麻烦,对于数据量较大的情况,在此与大家共享使用SteamWriter类输出Excel文件的方法。经过具体测试,通过在程序中使用多线程配置该方法,导出300000行+17列的约130M的数据需要31秒左右。
B/S 导出:
- // 保存错误信息
- GridView gv = new GridView();
- gv.DataSource = dtError;
- gv.DataBind();
- gv.Attributes.Add("style", "vnd.ms-excel.numberformat:@");
- HttpResponse hResponse = this.Response;
- string fileName1 = "新员工格式验证错误统计" + DateTime.Now.ToString("yyyyMMdd");
- hresponse.addheader("Content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName1, System.Text.Encoding.UTF8) + ".xls");
- hResponse.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
- hResponse.ContentType = "application/ms-excel";
- this.EnableViewState = false;
- StringWriter tw = new StringWriter();
- System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
- gv.RenderControl(hw);
- hResponse.Write(tw);
- hResponse.End();