1、引言
1.1解決哪些問題
現在很多公司用的導出基本上采用的通過gridView導出excel,此種導出存在以下幾種問題
1、數據量大的時候有時導出有時會讓瀏覽器卡死,因為導出的excel不是真正的excel,是html格式的,只是用excel打開,查看方式只需用記事本或其他文本編輯器打開就行了。
2、 由於導出的是html,用excel打開,會出現以下兩個問題:1、所以導出的數據都會彈出一個提示框,“您嘗試打開的文件的格式與文件擴展名指定格式不一致,打開文件前請驗證文件沒有損壞且來源可信”的對話框2、當修改里面的內容時只能保存一個副本操作及其不方便。3、而且html格式的文檔導入也會存在很大的問題。
1.2未解決的問題
1、NPOI導出2007格式和2010格式的很慢,幾萬數據很可能會卡死。
2、 NPOI
2. 1 NPOI簡介
NPOI 是 POI 項目的 .NET 版本。POI是一個開源的Java讀寫Excel、WORD等微軟OLE2組件文檔的項目。
使用 NPOI 你就可以在沒有安裝 Office 或者相應環境的機器上對 WORD/EXCEL 文檔進行讀寫。NPOI是構建在POI 3.x版本之上的,它可以在沒有安裝Office的情況下對 Word/Excel文檔進行讀寫操作
2.2 NPOI優勢
(一)傳統操作Excel遇到的問題:
1、如果是.NET,需要在服務器端裝Office,且及時更新它,以防漏洞,還需要設定權限允許.NET訪問COM+,如果在導出過程中出問題可能導致服務器宕機。
2、Excel會把只包含數字的列進行類型轉換,本來是文本型的,Excel會將其轉成數值型的,比如編號000123會變成123。
3、導出時,如果字段內容以“-”或“=”開頭,Excel會把它當成公式進行,會報錯。
4、Excel會根據Excel文件前8行分析數據類型,如果正好你前8行某一列只是數字,那它會認為該列為數值型,自動將該列轉變成類似1.42702E+17格式,日期列變成包含日期和數字的。
5、第二種是直接導出html,修改后綴名為.xls,這個方法有點像騙人的把戲,而且不能再導入
6、第三種是使用Jet OLEDB引擎來進行導入導出,完全使用sql語句來進行操作,缺點能控制的東西非常有限,比如格式就難以控制
7、第四中CSV格式的文件其實導出的是文本格式的文件,此種格式的文件優點導出方便而且速度快。但是使用者用excel對數據進行分析后需要對數據進行重新存一份。
(二)使用NPOI的優勢
1、你不需要在服務器上安裝微軟的Office,可以避免版權問題。
2、使用起來比Office PIA的API更加方便,更人性化。
3、你不用去花大力氣維護NPOI,NPOI Team會不斷更新、改善NPOI,絕對省成本。
NPOI之所以強大,並不是因為它支持導出Excel,而是因為它支持導入Excel,並能“理解”OLE2文檔結構,這也是其他一些Excel讀寫庫比較弱的方面。通常,讀入並理解結構 遠比導出來得復雜,因為導入你必須假設一切情況都是可能的,而生成你只要保證滿足你自己需求就可以了,如果把導入需求和生成需求比做兩個集合,那么生成需求通常都是導入需求的子集,這一規律不僅體現在Excel讀寫庫中,也體現在pdf讀寫庫中,目前市面上大部分的pdf庫僅支持生成,不支持導入。
4、支持excel07格式和簡單的10格式的導入導出
5、支持圖片的導入導出
6、導入導出速度很快
2.3 NPOI組件構成
NPOI 2.01,當是.net2.0框架時提供以下使用的dll和配置文件。
1、 ICSharpCode.SharpZipLib.dll
2、 NPOI.dll
3、 NPOI.OOXML.dll
4、 NPOI.OpenXml4Net.dll
5、 NPOI.OpenXml4Net.dll.config
6、 NPOI.OpenXmlFormats.dll
7、 NPOI.XML
如果是.net 3.5框架時提供以下使用的dll和配置文件
1、 ICSharpCode.SharpZipLib.dll
2、 NPOI.dll
3、 NPOI.OOXML.dll
4、 NPOI.OpenXml4Net.dll
5、 NPOI.OpenXml4Net.dll.config
6、 NPOI.OpenXmlFormats.dll
7、 NPOI.XML
如果是.net 4.0框架時提供以下使用的dll和配置文件
1、 ICSharpCode.SharpZipLib.dll
2、 NPOI.dll
3、 NPOI.OOXML.dll
4、 NPOI.OpenXml4Net.dll
5、 NPOI.OpenXmlFormats.dll
6、 NPOI.XML
2.4 如何使用NPOI
2.4.1 使用准備
將新建項目時所使用的.net框架版本和NPOI相對應,然后對所有dll添加引用
2.4.2 NPOI組件dll詳細情況
1、NPOI.DLL中包含的模塊
NPOI.Util 基礎輔助庫
NPOI.POIFS OLE2格式讀寫庫,主要負責處理DocumentInformation
NPOI.DDF Microsoft Drawing格式讀寫庫
NPOI.SS Excel 2003和Excel 2007操作庫共用的接口庫以及公用模塊實現,如公式計算庫
NPOI.HPSF OLE2的Summary Information和Document Summary Information屬性讀寫庫
NPOI.HSSF Excel BIFF格式讀寫庫,這是用戶用的最多的命名空間
2、NPOI.OOXML中包含的模塊
NPOI.XSSF Excel 2007操作庫,大部分對象都實現了NPOI.SS的接口
NPOI.XWPF Word 2007操作庫
3、NPOI.OpenXml4Net.DLL中包含的模塊
只有一個,即NPOI.OpenXml4Net,它是從POI的子項目OpenXml4j移植過來的,其功能類似於NPOI.POIFS,只是它操作的是OOXML格式。這個模塊和微軟提供的 System.Packaging功能是一致的,只是System.Packaging支持.Net 3.0以上,這個支持.NET 2.0。
4、NPOI.OpenXmlFormats.DLL中包含的模塊
也只有一個,即OpenXmlFormats,它定義了所有OOXML對象和C#對象的映射關系,並協助進行序列化和反序列化,從而使文件讀寫層和邏輯層分離。
2.4.3 使用操作
1、取數據操作,由於導出的數據量很大,不能一次將數據取到內存中,需要分配的將數據取到內存中
Demo中分批取數據方法
1 BATOStatisticsRPT bllATO = new BATOStatisticsRPT(); 2 // 由於導出數據量很大 分頁服務取得的數據很大所以分批取數據放到DataTable中 3 MyPager pager = new MyPager(); 4 5 pager.PageSize = 5000;//每次取5000條數據 6 7 pager.TotalSize = bllATO.GetRecord(); 8 9 int pageCount = pager.GetPageCount(); 10 11 DataTable dt = new DataTable(); 12 13 for (int i = 0; i < pageCount; i++) 14 15 { 16 17 DataTable dtTemp = new DataTable(); 18 19 dtTemp = bllATO.GetDataTable("", "", pager.PageSize * i, pager.PageSize * (i + 1)); 20 21 dt.Merge(dtTemp); 22 23 } 24 25 return dt;
其中有一個簡單分頁類代碼為:
/// <summary> /// MyPager類 /// </summary> public class MyPager { /// <summary> /// 總條數 /// </summary> public int TotalSize { get; set; } /// <summary> /// 每頁數據量 /// </summary> public int PageSize { get; set; } /// <summary> /// 當前頁面 /// </summary> public int CurrentPageIndex { get; set; } /// <summary> /// 得到總頁數 /// </summary> /// <returns>總頁數</returns> public int GetPageCount() { int totalPageCount; return totalPageCount = (int)Math.Ceiling((double)TotalSize / PageSize); } }
3、導出excel2003格式
NPOIHelper.TableToExcelForXLSAny(this.GetDataTable(), "excel2003導出");
NPOIHelPer代碼幫助類代碼為
/// <summary> /// NPOIHelper類 /// </summary> public class NPOIHelper { #region excel2003超過65535行數據用多個sheet處理 /// <summary> /// 將DataTable數據導出到Excel文件中(xls) 最大支持65535行 /// </summary> /// <param name="dt">數據源</param> /// <param name="excelName">導出文件名稱</param> public static void TableToExcelForXLSAny(DataTable dt, string excelName) { Stopwatch stopWacth = new Stopwatch(); stopWacth.Start();// 開始計時器 HSSFWorkbook hssfworkbook = new HSSFWorkbook(); int rowCount = dt.Rows.Count; int sheetMaxRow = 65535; //大於65535行數據 if (rowCount > sheetMaxRow) { for (int k = 1; k <= rowCount / sheetMaxRow; k++) { ISheet sheet = hssfworkbook.CreateSheet(excelName + "_" + k); //表頭 IRow row = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { sheet.SetColumnWidth(i, 30 * 180);// 設置所在列的寬度 ICell cell = row.CreateCell(i); cell.SetCellValue(dt.Columns[i].ColumnName); } int m = 0; //數據 for (int i = (k - 1) * sheetMaxRow; i < k * sheetMaxRow; i++) { IRow row1 = sheet.CreateRow(m + 1); for (int j = 0; j < dt.Columns.Count; j++) { ICell cell = row1.CreateCell(j); cell.SetCellValue(dt.Rows[i][j].ToString()); } m++; } } if (rowCount % sheetMaxRow != 0) { ISheet sheet = hssfworkbook.CreateSheet(excelName + "_" + (rowCount / sheetMaxRow + 1)); //表頭 IRow row = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { sheet.SetColumnWidth(i, 30 * 180);// 設置所在列的寬度 ICell cell = row.CreateCell(i); cell.SetCellValue(dt.Columns[i].ColumnName); } int m = 0; //數據 for (int i = (rowCount / sheetMaxRow) * sheetMaxRow; i < rowCount; i++) { IRow row1 = sheet.CreateRow(m + 1); for (int j = 0; j < dt.Columns.Count; j++) { ICell cell = row1.CreateCell(j); cell.SetCellValue(dt.Rows[i][j].ToString()); } m++; } } } // 小於65536行 else { ISheet sheet = hssfworkbook.CreateSheet(excelName); //表頭 IRow row = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { sheet.SetColumnWidth(i, 30 * 180);// 設置所在列的寬度 ICell cell = row.CreateCell(i); cell.SetCellValue(dt.Columns[i].ColumnName); } //數據 for (int i = 0; i < dt.Rows.Count; i++) { IRow row1 = sheet.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count; j++) { ICell cell = row1.CreateCell(j); cell.SetCellValue(dt.Rows[i][j].ToString()); } } } System.Web.HttpContext curContext = System.Web.HttpContext.Current; curContext.Response.Clear(); curContext.Response.ContentType = "application/x-excel"; string filename = HttpUtility.UrlEncode(excelName + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls"); curContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename); hssfworkbook.Write(curContext.Response.OutputStream); File.AppendAllText(curContext.Server.MapPath("/TestMinutes/TestResult.txt"), "\nNPOI得到dataTable后導出數據速度:" + stopWacth.ElapsedMilliseconds.ToString()+"毫秒", System.Text.Encoding.UTF8); stopWacth.Stop(); curContext.Response.End(); } #endregion #region Excel2003 /// <summary> /// 將Excel文件中的數據讀出到DataTable中(xls) /// </summary> /// <param name="file">文件路徑</param> /// <returns>DataTable</returns> public static DataTable ExcelToTableForXLS(string file) { DataTable dt = new DataTable(); using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { HSSFWorkbook hssfworkbook = new HSSFWorkbook(fs); ISheet sheet = hssfworkbook.GetSheetAt(0); //表頭 IRow header = sheet.GetRow(sheet.FirstRowNum); List<int> columns = new List<int>(); for (int i = 0; i < header.LastCellNum; i++) { object obj = GetValueTypeForXLS(header.GetCell(i) as HSSFCell); if (obj == null || obj.ToString() == string.Empty) { dt.Columns.Add(new DataColumn("Columns" + i.ToString())); //continue; } else dt.Columns.Add(new DataColumn(obj.ToString())); columns.Add(i); } //數據 for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++) { DataRow dr = dt.NewRow(); bool hasValue = false; foreach (int j in columns) { dr[j] = GetValueTypeForXLS(sheet.GetRow(i).GetCell(j) as HSSFCell); if (dr[j] != null && dr[j].ToString() != string.Empty) { hasValue = true; } } if (hasValue) { dt.Rows.Add(dr); } } } return dt; } /// <summary> /// 將DataTable數據導出到Excel文件中(xls) /// </summary> /// <param name="dt">數據源</param> /// <param name="excelName">excel名稱</param> public static void TableToExcelForXLS(DataTable dt, string excelName) { HSSFWorkbook hssfworkbook = new HSSFWorkbook(); ISheet sheet = hssfworkbook.CreateSheet("Test"); //表頭 IRow row = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { ICell cell = row.CreateCell(i); cell.SetCellValue(dt.Columns[i].ColumnName); } //數據 for (int i = 0; i < dt.Rows.Count; i++) { IRow row1 = sheet.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count; j++) { ICell cell = row1.CreateCell(j); cell.SetCellValue(dt.Rows[i][j].ToString()); } } System.Web.HttpContext curContext = System.Web.HttpContext.Current; curContext.Response.Clear(); curContext.Response.ContentType = "application/x-excel"; string filename = HttpUtility.UrlEncode(excelName + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls"); curContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename); hssfworkbook.Write(curContext.Response.OutputStream); curContext.Response.End(); } /// <summary> /// 獲取單元格類型(xls) /// </summary> /// <param name="cell">單元格</param> /// <returns>單元格類型</returns> private static object GetValueTypeForXLS(HSSFCell cell) { if (cell == null) return null; switch (cell.CellType) { case CellType.BLANK: //BLANK: return null; case CellType.BOOLEAN: //BOOLEAN: return cell.BooleanCellValue; case CellType.NUMERIC: //NUMERIC: return cell.NumericCellValue; case CellType.STRING: //STRING: return cell.StringCellValue; case CellType.ERROR: //ERROR: return cell.ErrorCellValue; case CellType.FORMULA: //FORMULA: default: return "=" + cell.CellFormula; } } #endregion #region Excel2007和簡單的Excel2010 /// <summary> /// 將Excel文件中的數據讀出到DataTable中(xlsx) /// </summary> /// <param name="file">文件路徑</param> /// <returns>DataTable</returns> public static DataTable ExcelToTableForXLSX(string file) { DataTable dt = new DataTable(); using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { XSSFWorkbook xssfworkbook = new XSSFWorkbook(fs); ISheet sheet = xssfworkbook.GetSheetAt(0); // 表頭 IRow header = sheet.GetRow(sheet.FirstRowNum); List<int> columns = new List<int>(); for (int i = 0; i < header.LastCellNum; i++) { object obj = GetValueTypeForXLSX(header.GetCell(i) as XSSFCell); if (obj == null || obj.ToString() == string.Empty) { dt.Columns.Add(new DataColumn("Columns" + i.ToString())); // continue; } else dt.Columns.Add(new DataColumn(obj.ToString())); columns.Add(i); } // 數據 for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++) { DataRow dr = dt.NewRow(); bool hasValue = false; foreach (int j in columns) { dr[j] = GetValueTypeForXLSX(sheet.GetRow(i).GetCell(j) as XSSFCell); if (dr[j] != null && dr[j].ToString() != string.Empty) { hasValue = true; } } if (hasValue) { dt.Rows.Add(dr); } } } return dt; } /// <summary> /// 將DataTable數據導出到Excel文件中(xlsx) /// </summary> /// <param name="dt">數據源</param> /// <param name="excelName">文件名稱</param> public static void TableToExcelForXLSX(DataTable dt, string excelName) { XSSFWorkbook xssfworkbook = new XSSFWorkbook(); ISheet sheet = xssfworkbook.CreateSheet("Test"); //表頭 IRow row = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { ICell cell = row.CreateCell(i); cell.SetCellValue(dt.Columns[i].ColumnName); } //數據 for (int i = 0; i < dt.Rows.Count; i++) { IRow row1 = sheet.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count; j++) { ICell cell = row1.CreateCell(j); cell.SetCellValue(dt.Rows[i][j].ToString()); } } System.Web.HttpContext curContext = System.Web.HttpContext.Current; curContext.Response.Clear(); curContext.Response.ContentType = "application/x-excel"; string filename = HttpUtility.UrlEncode(excelName + DateTime.Now.ToString("yyyyMMddHHmm") + ".xlsx"); curContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename); xssfworkbook.Write(curContext.Response.OutputStream); curContext.Response.End(); } /// <summary> /// 獲取單元格類型(xlsx) /// </summary> /// <param name="cell">單元格</param> /// <returns>單元格類型</returns> private static object GetValueTypeForXLSX(XSSFCell cell) { if (cell == null) return null; switch (cell.CellType) { case CellType.BLANK: //BLANK: return null; case CellType.BOOLEAN: //BOOLEAN: return cell.BooleanCellValue; case CellType.NUMERIC: //NUMERIC: return cell.NumericCellValue; case CellType.STRING: //STRING: return cell.StringCellValue; case CellType.ERROR: //ERROR: return cell.ErrorCellValue; case CellType.FORMULA: //FORMULA: default: return "=" + cell.CellFormula; } } #endregion }
TableToExcelForXLSAny方法中第一個參數為DataTable,第二個參數為報表名稱 ,調用此方法時,由於excel2003每個sheet最多支持65535行數據,如果導出的數據量大於65535行時,會分為多個sheet。
4、導出excel2007格式
NPOIHelper.TableToExcelForXLSX(this.GetDataTable(), "excel2007或者excel2010導出");
TableToExcelForXLSX方法中第一個參數為DataTable,第二個參數為報表名稱
5、將excel2003導入到DataTable中
DataTable dt = NPOIHelper.ExcelToTableForXLS(Server.MapPath("/TestFile/excel2003導入.xls"));
ExcelToTableForXLS中的參數為導入文件的物理路徑
6、將excel2007導入到DataTable中
DataTable dt = NPOIHelper.ExcelToTableForXLSX(Server.MapPath("/TestFile/excel2007或者excel2010導入.xlsx"));
ExcelToTableForXLSX中的參數為導入文件的物理路徑
2.5 其他導出幫助類代碼
CSV導出幫助類代碼
1 /// <summary> 2 /// CSVHelper類 3 /// </summary> 4 public class CSVHelper 5 { 6 /// <summary> 7 /// 導出CSV格式 8 /// </summary> 9 /// <param name="dt">數據源</param> 10 /// <param name="FileName">保存的文件名稱</param> 11 public static void DataTableToCSV(DataTable dt, string FileName) 12 { 13 Stopwatch stopWacth = new Stopwatch(); 14 stopWacth.Start();// 開始計時器 15 StringWriter sw = new StringWriter(); 16 StringBuilder sb = new StringBuilder(); 17 18 //得到列名 19 for (int i = 0; i < dt.Columns.Count; i++) 20 { 21 sb.Append(dt.Columns[i].ColumnName); 22 if (i != dt.Columns.Count - 1) 23 { 24 sb.Append(","); 25 } 26 } 27 sw.WriteLine(sb.ToString()); 28 29 //得到每列的數據 30 foreach (DataRow dr in dt.Rows) 31 { 32 for (int i = 0; i < dt.Columns.Count; i++) 33 { 34 sw.Write(dr[i]); 35 if (i != dt.Columns.Count - 1) 36 { 37 sw.Write(","); 38 } 39 } 40 41 sw.WriteLine(""); 42 } 43 44 sw.Close(); 45 System.Web.HttpContext curContext = System.Web.HttpContext.Current; 46 curContext.Response.Clear(); 47 curContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + curContext.Server.UrlEncode(FileName) + ".csv"); 48 curContext.Response.ContentType = "application/ms-excel"; 49 curContext.Response.ContentEncoding = System.Text.Encoding.Default; // 采用默認編碼輸出 50 curContext.Response.Write(sw); 51 File.AppendAllText(curContext.Server.MapPath("/TestMinutes/TestResult.txt"), "\nCSV得到dataTable后導出數據速度:"+stopWacth.ElapsedMilliseconds.ToString()+"毫秒", System.Text.Encoding.UTF8); 52 stopWacth.Stop(); 53 curContext.Response.End(); 54 } 55 }
2.6 附加說明
CSV和NPOI的比較
CSV文件簡單說明:
每條記錄占一行
以逗號為分隔符
逗號前后的空格會被忽略
字段中包含有逗號,該字段必須用雙引號括起來
字段中包含有換行符,該字段必須用雙引號括起來
字段前后包含有空格,該字段必須用雙引號括起來
字段中的雙引號用兩個雙引號表示
字段中如果有雙引號,該字段必須用雙引號括起來
字段中如果有太長的數字,該字段必須單引號括起來
日期格式不用做特殊處理
第一條記錄,可以是字段名
CSV優點:
CSV格式的文件其實導出的是文本格式的文件,此種格式的文件優點導出方便而且比NPOI速度快。
CSV缺點:
使用者用excel對數據進行分析后需要對數據進行重新存一份。
最后把用datatable直接導出html附上(實質上是騙人的把戲,是文本格式的數據)
/// <summary> /// 通過GRIDVIEW導出EXCEL /// </summary> /// <param name="dtData">數據源</param> /// <param name="excelName">導出的excel名</param> public void ExportExcelForGridView(System.Data.DataTable dtData, string excelName) { System.Web.UI.WebControls.GridView GridGy = null; string FileName = HttpUtility.UrlEncode(excelName + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls");// "CgsReport" + DateTime.Now.Date.ToString("yyyyMMddHHmm") + ".xls"; System.Web.HttpContext curContext = System.Web.HttpContext.Current; if (dtData != null) { GridGy = new System.Web.UI.WebControls.GridView(); GridGy.AllowPaging = false; GridGy.Visible = true; GridGy.DataSource = dtData; GridGy.RowDataBound += new GridViewRowEventHandler(GridGy_RowDataBound); GridGy.DataBind(); } curContext.Response.ClearContent(); curContext.Response.AddHeader("content-disposition", "attachment;filename=" + "" + FileName); curContext.Response.Charset = "GB2312"; curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); curContext.Response.ContentType = "application/vnd.ms-excel"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); GridGy.RenderControl(htmlWrite); string top = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<title>Datos</title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=GB2312\" />\n<style>\n</style>\n</head>\n<body>\n"; string end = "</body></html>"; curContext.Response.Write(top + stringWrite.ToString() + end); // curContext.Response.End(); dtData.Dispose(); }