使用c#导出到具有大内存流的Excel

时间:2016-12-07 10:23:06

标签: c# asp.net-mvc

我正在使用此代码

 using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(ds);
                wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                wb.Style.Font.Bold = true;
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.Charset = "";
                HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename= EmployeeAndOrderReport.xlsx");
                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    wb.SaveAs(MyMemoryStream);
                    MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
                    HttpContext.Current.Response.Flush();
                    HttpContext.Current.Response.End();
                }
            }

它的工作正常但是当我导出大型记录集时,它显示出内存异常..为什么它显示这样?

1 个答案:

答案 0 :(得分:1)

我发布我的解决方案..我认为最好将大文件导出为ex​​cels ..只需安装EPPLUS nuget包。

`ExcelPackage excel = new ExcelPackage();
 var userSheet = excel.Workbook.Worksheets.Add("DB_USER");
 userSheet.Cells["A1"].LoadFromCollection(salaryReportlistObj, true);
 using (var memoryStream = new MemoryStream())
 {
                HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;  filename=Dane.xlsx");
                excel.SaveAs(memoryStream);
                memoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
 }

`