2017-02-27 191 views
0

我試圖使用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:我真的想知道如何生成一個文件進行下載,也就是說,爲什麼你的代碼工作,瀏覽器生成文件或服務器?

+0

so ..你的代碼不工作,或者你有一個問題嗎? – lordkain

+0

@lordkain我的代碼無效。如果你有代碼的作品,我想知道它是如何工作:) –

+0

youre使用經典的asp.net或MVC – lordkain

回答

0

NPOI是一個輔助模塊,用於創建四個excel文件。這是在服務器端和內存中創建的。 (workbook.Write(ms)將excel文件寫入內存)excel文件以字節[]的形式通過網絡,瀏覽器根據文件和內容類型決定如何處理它。

當u使用經典的asp.net然後把一個鏈接在你的aspx頁面像下面

<a target="_blank" href="Handler.ashx" >download...</a> 

創建Handler.ashx並把代碼FOM DownloadExcel成的ProcessRequest從Handler.ashx。

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); 
} 
+0

我已經將contenttype設置爲「application/vnd.ms-excel」,但我仍然得到二進制流。 –

0

我用過ajax TVT。

window.location.href = "?action=DownloadAll"; 
    //$.ajax({ 
    // url: "?action=DownloadAll", 
    // type: "get", 
    // success: function() { } 
    //}); 
0

你可以把一個DataTable到Excel工作表有一些非常可讀的代碼:

XLWorkbook wb = new XLWorkbook(); 
DataTable dt = GetDataTableOrWhatever(); 
wb.Worksheets.Add(dt,"WorksheetName"); 

它將運行速度超快呢!