码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-11-28 15:43:16      阅读:320      评论:0      收藏:0      [点我收藏+]

标签:ble   ++   tco   客户端   上下文   oda   tostring   ceil   row   

代码段  

/// <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自动分表

标签:ble   ++   tco   客户端   上下文   oda   tostring   ceil   row   

原文地址:http://www.cnblogs.com/lacey/p/6109399.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!