.NET ez 2012-05-10
利用 NPOI 即可將 DataSet 匯出到 Excel 檔案。
官方網站:http://npoi.codeplex.com/
本地DLL下載:NPOI v1.25 .NET3.5 (已修改版可以超過4000條style限制)
程式碼範例:
DataSet DS = new DataSet(); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("工作表名稱"); //顯示 Table 0 的所有欄位名稱 HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0); foreach (DataColumn column in DS.Tables[0].Columns) { headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); } //顯示 所有資料列 int rowIndex = 1; foreach (DataRow row in DS.Tables[0].Rows) { HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex); foreach (DataColumn column in DS.Tables[0].Columns) { dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString()); } dataRow = null; rowIndex++; } Response.Clear(); // 產生 Excel 資料流 MemoryStream ms = new MemoryStream(); workbook.Write(ms); headerRow = null; sheet = null; workbook = null; // 設定強制下載標頭 Response.AddHeader("Content-Disposition", string.Format("attachment; filename=Download.xls")); // 輸出檔案 Response.BinaryWrite(ms.ToArray()); ms.Close(); ms.Dispose(); Response.End();
標籤: .NET
本文章網址:
https://www.ez2o.com/Blog/Post/csharp-Excel-NPOI-Sample-Code
https://www.ez2o.com/Blog/Post/179
https://www.ez2o.com/Blog/Post/csharp-Excel-NPOI-Sample-Code
https://www.ez2o.com/Blog/Post/179