npoi2.0將datatable對象轉(zhuǎn)換為excel2007示例
更新時間:2014年04月24日 10:17:15 作者:
這篇文章主要介紹了npoi2.0將datatable對象轉(zhuǎn)換為excel2007示例的相關(guān)資料
NPOI 2.0將DataTable對象轉(zhuǎn)換為Excel 2007文件提供下載
復(fù)制代碼 代碼如下:
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;
}
//列寬自適應(yīng),只對英文和數(shù)字有效
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("出錯,無法下載!");
}
您可能感興趣的文章:
相關(guān)文章
詳解WPF雙滑塊控件的使用和強制捕獲鼠標(biāo)事件焦點
這篇文章主要為大家詳細介紹了WPF中雙滑塊控件的使用和強制捕獲鼠標(biāo)事件焦點的實現(xiàn),文中的示例代碼講解詳細,感興趣的可以嘗試一下2022-07-07C#調(diào)用百度翻譯實現(xiàn)翻譯HALCON的示例
HALCON示例程序的描述部分一直是英文的,看起來很不方便。本文就使用百度翻譯實現(xiàn)翻譯HALCON,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-06-06