C#问题:怎么样用IO流快速导出大量的数据到Excel中,现在遇到内存溢出问题。
excel一个工作表只能存放65535条数据,现在大量的数据导入到excel中就出现内存溢出,怎么样建立多个工作表来存放这些大量的数据呢?...
excel一个工作表只能存放65535条数据,现在大量的数据导入到excel中就出现内存溢出,怎么样建立多个工作表来存放这些大量的数据呢?
展开
展开全部
给个思路.给点代码:
/// <summary>
/// 下载Excel文件
/// </summary>
/// <param name="context"></param>
/// <param name="dt"></param>
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
后面压缩下载
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询