C#问题:怎么样用IO流快速导出大量的数据到Excel中,现在遇到内存溢出问题。

2024-11-08 19:46:52
推荐回答(1个)
回答(1):

给个思路.给点代码:

        /// 
        /// 下载Excel文件
        /// 

        /// 
        /// 
        public static void ExportXls(HttpContext context, DataTable dt, string columns)
        {
            HSSFWorkbook book = new HSSFWorkbook();

            //超过5W条分Sheet
            int sheetCount = dt.Rows.Count % 50000 == 0 ? dt.Rows.Count / 50000 : dt.Rows.Count / 50000 + 1;
            ISheet sheet = null;
            IRow row = null;
            ICell cell = null;
            for (int i = 0; i != sheetCount; i++)
            {
                sheet = book.CreateSheet(string.Format("不告诉你", i + 1));
                row = sheet.GetRow(0) ?? sheet.CreateRow(0);
                for (int k = 0; k != dt.Columns.Count; k++)
                {
                    cell = row.GetCell(k) ?? row.CreateCell(k);
                    cell.SetCellValue(dt.Columns[k].ColumnName);
                }
            }


            for (int i = 0; i != dt.Rows.Count; i++)
            {
                sheet = book.GetSheetAt(i / 50000);
                row = sheet.GetRow(i - (i / 50000) * 50000 + 1) ?? sheet.CreateRow(i - (i / 50000) * 50000 + 1);
                for (int k = 0; k != dt.Columns.Count; k++)
                {
                    cell = row.GetCell(k) ?? row.CreateCell(k);

                    if (dt.Rows[i][k] != DBNull.Value)
                    {
                        cell.SetCellValue(dt.Rows[i][k].ToString());
                    }
                }
            }
            string now = DateTime.Now.ToString("yyyyMMdd");
            string zipName = string.Format("还是不告诉你.zip", now);
            string fileName = string.Format("还是不告诉你.xls", now);

            context.Response.ContentType = "application/octet-stream;charset=UTF-8";
            context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", zipName));
            context.Response.Clear();

            ZipOutputStream zipOutputStream = new ZipOutputStream(context.Response.OutputStream);
            zipOutputStream.SetLevel(6); //0-9, 9 being the highest level of compression
            后面压缩下载
        }