[英]How to export a DataTable variable to EXCEL and download the excel
我正在嘗試像這樣使用NPOI:
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:我真的很想知道如何生成要下載的文件,也就是說,為什么您的代碼有效,瀏覽器還是要生成文件或服務器?
NPOI是創建四個您的Excel文件的幫助器模塊。 這是在服務器端和內存中創建的。 ( workbook.Write(ms)將excel文件寫入內存中)excel文件作為字節[]通過網絡傳輸,瀏覽器根據文件和內容類型決定如何處理它。
當您使用經典的asp.net時,請在您的aspx頁面中放置一個鏈接,如下所示
<a target="_blank" href="Handler.ashx" >download...</a>
創建一個Handler.ashx,並將DownloadExcel的代碼放入Handler.ashx的ProcessRequest中。
public void ProcessRequest (HttpContext context)
{
//create dumy data, or in youre case the data form somewhere else
DataTable table = new DataTable();
table.Columns.AddRange(new[]
{
new DataColumn("Name")
});
table.Rows.Add("david");
table.Rows.Add("Ruud");
// your code
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");
}
}
在MVC中,如下所示。
[HttpGet]
public ActionResult ExportToExcel(string reportName)
{
byte [] reportDocument = RenderDataTableToExcel().ToArray();
Response.StatusCode = (int)HttpStatusCode.OK;
return File(reportDocument, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", reportName);
}
我用過ajax TVT。
window.location.href = "?action=DownloadAll";
//$.ajax({
// url: "?action=DownloadAll",
// type: "get",
// success: function () { }
//});
您可以使用一些易讀的代碼將DataTable轉換為Excel工作表:
XLWorkbook wb = new XLWorkbook();
DataTable dt = GetDataTableOrWhatever();
wb.Worksheets.Add(dt,"WorksheetName");
它也將超快運行!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.