首页 > 代码库 > NPOI 导出excel数据超65535自动分表

NPOI 导出excel数据超65535自动分表

代码段  

/// <summary>
/// DataTable转换成Excel文档流,并输出到客户端
/// </summary>
/// <param name="table"></param>
/// <param name="response"></param>
/// <param name="fileName">输出的文件名</param>
public static void RenderToDataTableToExcel(DataTable table, HttpContext context, string fileName)
{
using (MemoryStream ms = ExportDataTableToExcel(table))
{
RenderToBrowser(ms, context, fileName);
}
}

 

 

/// <summary>
/// DataTable转换成Excel文档流(导出数据量超出65535条,分sheet)
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public static MemoryStream ExportDataTableToExcel(DataTable sourceTable)
{
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
int dtRowsCount = sourceTable.Rows.Count;
int SheetCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(dtRowsCount) / 65536));
int SheetNum = 1;
int rowIndex = 1;
int tempIndex = 1; //标示 
ISheet sheet = workbook.CreateSheet("sheet1" + SheetNum);
for (int i = 0; i < dtRowsCount; i++)
{
if (i == 0 || tempIndex == 1)
{
IRow headerRow = sheet.CreateRow(0);
foreach (DataColumn column in sourceTable.Columns)
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
}
HSSFRow dataRow = (HSSFRow)sheet.CreateRow(tempIndex);
foreach (DataColumn column in sourceTable.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(sourceTable.Rows[i][column].ToString());
}
if (tempIndex == 65535)
{
SheetNum++;
sheet = workbook.CreateSheet("sheet" + SheetNum);//
tempIndex = 0;
}
rowIndex++;
tempIndex++;
//AutoSizeColumns(sheet);
}
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
sheet = null;
// headerRow = null;
workbook = null;
return ms;
}

 

 

/// <summary>
/// 输出文件到浏览器
/// </summary>
/// <param name="ms">Excel文档流</param>
/// <param name="context">HTTP上下文</param>
/// <param name="fileName">文件名</param>
private static void RenderToBrowser(MemoryStream ms, HttpContext context, string fileName)
{
if (context.Request.Browser.Browser == "IE")
fileName = HttpUtility.UrlEncode(fileName);
context.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);
context.Response.BinaryWrite(ms.ToArray());
}

NPOI 导出excel数据超65535自动分表