[C#] Excel匯出幫助類
阿新 • • 發佈:2019-01-22
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using Excel = Microsoft.Office.Interop.Excel; namespace Common { public class ExcelHelper { public static string Pbint; /// <summary> /// 將DataTable中的資料匯出到excel中 /// </summary> /// <param name="dsT"></param> /// <param name="saveFileName">儲存路徑</param> /// <param name="bookname">表格頭 可以為空串</param> /// <returns></returns> public static string ExportExcel(DataTable dsT, string saveFileName, string bookname) { DataSet ds1 = new DataSet(); try { ds1.Tables.Add(dsT); //datatable轉為dataset // gridbind(); if (ds1 == null) return "表格為空"; Excel.Application xlApp = new Excel.Application(); object missing = System.Reflection.Missing.Value; if (xlApp == null) { return ("無法建立Excel物件,可能您的計算機可能沒有安裝Excel"); } Excel.Workbooks workbooks = xlApp.Workbooks; Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet); Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 Excel.Range range; long totalCount = ds1.Tables[0].Rows.Count; long rowRead = 0; float percent = 0; //寫入欄位 if (bookname == "") { //寫入標題 for (int i = 0; i < ds1.Tables[0].Columns.Count; i++) { worksheet.Cells[1, i + 1] = ds1.Tables[0].Columns[i].ColumnName; range = (Excel.Range)worksheet.Cells[1, i + 1]; range.Interior.ColorIndex = 20; range.Font.Bold = true; } //寫入數值 for (int r = 0; r < ds1.Tables[0].Rows.Count; r++) { for (int i = 0; i < ds1.Tables[0].Columns.Count; i++) { worksheet.Cells[r + 2, i + 1] = ds1.Tables[0].Rows[r][i]; } rowRead++; percent = ((float)(100 * rowRead)) / totalCount; Pbint = "正在匯出資料[" + percent.ToString("0.00") + "%]..."; } range = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[ds1.Tables[0].Rows.Count + 1, ds1.Tables[0].Columns.Count]]; range.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, null); range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic; range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous; range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin; if (ds1.Tables[0].Columns.Count > 1) { range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic; } } else { worksheet.Name = bookname; worksheet.Cells[1, 1] = bookname; range = (Excel.Range)worksheet.Cells[1, 1]; // range.Interior.ColorIndex = 10; range.Font.Bold = true; range.Font.Size = 12; range.RowHeight = 22; //行高 // range.Columns .AutoFilter(); //自動列寬 for (int i = 0; i < ds1.Tables[0].Columns.Count; i++) { worksheet.Cells[2, i + 1] = ds1.Tables[0].Columns[i].ColumnName; range = (Excel.Range)worksheet.Cells[2, i + 1]; range.Interior.ColorIndex = 15; range.Font.Bold = true; } //寫入數值 // Caption.Visible = true; for (int r = 0; r < ds1.Tables[0].Rows.Count; r++) { for (int i = 0; i < ds1.Tables[0].Columns.Count; i++) { worksheet.Cells[r + 3, i + 1] = ds1.Tables[0].Rows[r][i]; } rowRead++; percent = ((float)(100 * rowRead)) / totalCount; Pbint = "正在匯出資料[" + percent.ToString("0.00") + "%]..."; range = worksheet.Range[worksheet.Cells[2, 1], worksheet.Cells[ds1.Tables[0].Rows.Count + 2, ds1.Tables[0].Columns.Count]]; range.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, null); range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic; range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous; range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin; if (ds1.Tables[0].Columns.Count > 1) { range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic; } } } workbook.SaveAs(saveFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); workbook.Close(missing, missing, missing); xlApp.Quit(); } catch(Exception ex) { return ex.Message;//“object”未包含“get_Range”的定義 } return "匯出完成!"; } } }
注意該方式可能會由於Office的版本問題,出現方法簽名不一致的錯誤。
下面介紹通過NPOI方式下載檔案的方式,該方式的優點是不需要伺服器端安裝Office軟體。實現的思路是,首先使用者請求ashx一般處理程式,一般處理程式會查詢資料庫,然後將資料庫中的相關資訊儲存在DataTable中,再通過NPOI提供的介面方法,將DataTable中的資料儲存到本地,生成一個Excel檔案,最終ashx一般處理程式會生成一個URL連結,即為檔案在伺服器上的地址,前臺ajax請求的success處理函式中將請求重定向到該URL連結,即可實現檔案的下載。(注意需要下載NPOI.dll)
/// <summary> /// 實體類集合匯出到EXCLE2003 /// </summary> /// <param name="enList">資料來源</param> /// <param name="sheetName">工作表名稱</param> /// <returns>檔案的下載地址</returns> public static string EntityListToExcel2003(DataTable dTable) { try { string fileName = dTable.TableName + "-" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls"; // 檔名稱 string urlPath = "/Files/Excels/" + fileName; // 檔案下載的URL地址,供給前臺下載 string filePath = HttpContext.Current.Server.MapPath("\\" + urlPath); // 檔案路徑 // 1.檢測是否存在資料夾,若不存在就建立個資料夾 string directoryName = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } // 2.解析單元格頭部 HSSFWorkbook workbook = new HSSFWorkbook(); // 工作簿 ISheet sheet = workbook.CreateSheet(dTable.TableName); // 工作表 IRow row = sheet.CreateRow(0); // 設定列名稱 for (int i = 0; i < dTable.Columns.Count; i++) { row.CreateCell(i).SetCellValue(dTable.Columns[i].ColumnName); } // 3.List物件的值賦值到Excel的單元格里 for (int i = 1; i <= dTable.Rows.Count; i++) { IRow rowTmp = sheet.CreateRow(i); for (int j = 0; j < dTable.Columns.Count; j++) // 根據指定的屬性名稱,獲取物件指定屬性的值 { string cellValue = dTable.Rows[i - 1][j].ToString(); // 單元格的值 rowTmp.CreateCell(j).SetCellValue(cellValue); } } // 4.生成檔案 FileStream file = new FileStream(filePath, FileMode.Create); workbook.Write(file); file.Close(); // 5.返回下載路徑 return urlPath; } catch (Exception ex) { throw ex; } }
//資料匯出 function toExcel() { $.ajax({ url: '/JZ/JZHandler.ashx?action=ToExcel', type: 'POST', data: { JZId: $('#tt').tree('getRoot').text, Start: $('#dd1').datebox('getValue'), End: $('#dd2').datebox('getValue') }, beforeSend: function () { $.messager.progress({ text: '正在處理中...' }) }, success: function (data) { $.messager.progress('close'); data = eval('(' + data + ')'); //通過重定向到檔案的地址即可實現檔案的下載 location.href = data; } }); }