我試圖使用NPOI這樣的:如何一個DataTable變量導出到EXCEL和下載Excel
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 = s as MemoryStream;
Response.AddHeader("Content-Disposition", string.Format("attachment;filename=" + HttpUtility.UrlEncode(reportName) + DateTime.Now.ToString("yyyyMMdd") + ".xlsx"));
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Length", ms.ToArray().Length.ToString());
Response.BinaryWrite(ms.ToArray());
Response.Flush();
ms.Close();
ms.Dispose();
}
else
Response.Write("Error!Connot Download");
}
我有二進制流,而不是MS-Excel文件。 PS:我真的想知道如何生成一個文件進行下載,也就是說,爲什麼你的代碼工作,瀏覽器生成文件或服務器?
so ..你的代碼不工作,或者你有一個問題嗎? – lordkain
@lordkain我的代碼無效。如果你有代碼的作品,我想知道它是如何工作:) –
youre使用經典的asp.net或MVC – lordkain