npoi2.0将datatable对象转换为excel2007示例
npoi2.0将datatable对象转换为excel2007示例
发布时间:2016-12-28 来源:查字典编辑
摘要:NPOI2.0将DataTable对象转换为Excel2007文件提供下载复制代码代码如下:usingNPOI.SS.UserModel;u...

NPOI 2.0将DataTable对象转换为Excel 2007文件提供下载

复制代码 代码如下:

using NPOI.SS.UserModel;

using NPOI.XSSF.UserModel;

using System.IO;

private Stream RenderDataTableToExcel(DataTable SourceTable)

{

XSSFWorkbook workbook = null;

MemoryStream ms = null;

ISheet sheet = null;

XSSFRow headerRow = null;

try

{

workbook = new XSSFWorkbook();

ms = new MemoryStream();

sheet = workbook.CreateSheet();

headerRow = (XSSFRow)sheet.CreateRow(0);

foreach (DataColumn column in SourceTable.Columns)

headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);

int rowIndex = 1;

foreach (DataRow row in SourceTable.Rows)

{

XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);

foreach (DataColumn column in SourceTable.Columns)

dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());

++rowIndex;

}

//列宽自适应,只对英文和数字有效

for (int i = 0; i <= SourceTable.Columns.Count; ++i)

sheet.AutoSizeColumn(i);

workbook.Write(ms);

ms.Flush();

}

catch (Exception ex)

{

return null;

}

finally

{

ms.Close();

sheet = null;

headerRow = null;

workbook = null;

}

return ms;

}

private void DownloadExcel(DataTable dt,string reportName)

{

Stream s = RenderDataTableToExcel(dt);

if (s != null)

{

MemoryStream ms = resultStream.result as MemoryStream;

Response.AddHeader("Content-Disposition", string.Format("attachment;filename=" + HttpUtility.UrlEncode(reportName) + DateTime.Now.ToString("yyyyMMdd") + ".xlsx"));

Response.AddHeader("Content-Length", ms.ToArray().Length.ToString());

Response.BinaryWrite(ms.ToArray());

Response.Flush();

ms.Close();

ms.Dispose();

}

else

Response.Write("出错,无法下载!");

}

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新C#教程学习
热门C#教程学习
编程开发子分类