1. 程式人生 > >NET使用NPOI元件將資料匯出Excel-通用方法 【推薦】

NET使用NPOI元件將資料匯出Excel-通用方法 【推薦】

一、Excel匯入及匯出問題產生:

  從接觸.net到現在一直在維護一個DataTable匯出到Excel的類,時不時還會維護一個匯入類。以下是時不時就會出現的問題: 匯出問題:   如果是asp.net,你得在伺服器端裝Office,幾百M呢,還得及時更新它,以防漏洞,還得設定許可權允許ASP.net訪問COM+,聽說如果匯出過程中出問題可能導致伺服器宕機。   Excel會把只包含數字的列進行型別轉換,本來是文字型的,它非要把你轉成數值型的,像身份證後三位變成000,編號000123會變成123,夠智慧吧,夠鬱悶吧。不過這些都還是可以變通解決的,在他們前邊加上一個字母,讓他們不只包含數字。   匯出時,如果你的欄位內容以"-"或"="開頭,Excel好像把它當成了公式什麼的,接下來就出錯,提示:類似,儲存到Sheet1的問題 匯入問題:
  Excel會根據你的 Excel檔案前8行分析資料型別,如果正好你前8行某一列只是數字,那它會認為你這一列就是數值型的,然後,身份證,手機,編號都轉吧變成類似這樣的1.42702E+17格式,日期列變成 包含日期和數字的,亂的很,可以通過改登錄檔讓Excel分析整個表,但如果整列都是數字,那這個問題還是解決不了。   以上問題,一般人初次做時肯定得上網查查吧,一個問題接著另一個問題,查到你鬱郁而死,還有很多問題沒解決,最終感覺已經解決的不錯了,但還不能保證某一天還會出個什麼問題。

二、使用第三方開源元件匯入及匯出Excel的解決方案:

  偶然間發現了NPOI與MyXls,相見恨晚,害的我在Excel上浪費了那麼多時間,他們倆的好處是:就是.net的自定義類庫,可以直接對Excel進行讀或寫,而不依賴Office 的 Excel,這不管對於ASP.net或Winform都非常有利,不用擔心Excel程序的釋放問題,伺服器安全,設定,匯出,匯入“Excel智慧識別”,公式日期等問題,可以說以前的Excel問題,全都不用管了,它們可以很好的幫你解決,NPOI || MyXls == 研究幾年Excel。

三、下面來兩個簡單入門例子:

MyXls 快速入門例子: 複製程式碼
 /// <summary>
 /// MyXls簡單Demo,快速入門程式碼
 /// </summary>
 /// <param name="dtSource"></param>
 /// <param name="strFileName"></param>
 /// <remarks>MyXls認為Excel的第一個單元格是:(1,1)</remarks>
 public static void ExportEasy(DataTable dtSource,  string strFileName)
 {
     XlsDocument xls 
= new XlsDocument(); Worksheet sheet = xls.Workbook.Worksheets.Add("Sheet1"); //填充表頭 foreach (DataColumn col in dtSource.Columns) { sheet.Cells.Add(1, col.Ordinal + 1, col.ColumnName); } //填充內容 for (int i = 0; i < dtSource.Rows.Count; i++) { for (int j = 0; j < dtSource.Columns.Count; j++) { sheet.Cells.Add(i + 2, j + 1, dtSource.Rows[i][j].ToString()); } } //儲存 xls.FileName = strFileName; xls.Save(); }
複製程式碼 NPOI 快速入門例子: 複製程式碼
/// <summary>
 /// NPOI簡單Demo,快速入門程式碼
 /// </summary>
 /// <param name="dtSource"></param>
 /// <param name="strFileName"></param>
 /// <remarks>NPOI認為Excel的第一個單元格是:(0,0)</remarks>
 public static void ExportEasy(DataTable dtSource, string strFileName)
 {
     HSSFWorkbook workbook = new HSSFWorkbook();
     HSSFSheet sheet = workbook.CreateSheet();
 
     //填充表頭
     HSSFRow dataRow = sheet.CreateRow(0);
     foreach (DataColumn column in dtSource.Columns)
     {
         dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
     }
 
 
     //填充內容
     for (int i = 0; i < dtSource.Rows.Count; i++)
     {
         dataRow = sheet.CreateRow(i + 1);
         for (int j = 0; j < dtSource.Columns.Count; j++)
         {
             dataRow.CreateCell(j).SetCellValue(dtSource.Rows[i][j].ToString());
         }
     }
 
 
     //儲存
     using (MemoryStream ms = new MemoryStream())
     {
         using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
         {
             workbook.Write(fs);
         }
     }
     workbook.Dispose();
 }
複製程式碼

四、接下來是封裝的可以用在實際專案中的類,實現的功能有(僅NPOI):

  1. 支援web及winform從DataTable匯出到Excel。
  2. 生成速度很快。
  3. 準確判斷資料型別,不會出現身份證轉數值等上面提到的一系列問題。
  4. 如果單頁條數大於65535時會新建工作表。
  5. 列寬自適應。
  6. 支援讀取Excel。
  7. 呼叫方便,只一呼叫一個靜態類就OK了。
  8. 因為測試期間發現MyXls匯出速度要比NPOI慢3倍,而NPOI既能滿足我們的匯出需求,又能很好的滿足我們的匯入需求,所以只針對NPOI進行全方位功能實現及優化。
複製程式碼
NPOI操作類 

 using System;
 using System.Data;
 using System.Configuration;
 using System.Web;
 using System.Web.Security;
 using System.Web.UI;
 using System.Web.UI.HtmlControls;
 using System.Web.UI.WebControls;
 using System.Web.UI.WebControls.WebParts;
 using System.IO;
 using System.Text;
 using NPOI;
 using NPOI.HPSF;
 using NPOI.HSSF;
 using NPOI.HSSF.UserModel;
 using NPOI.HSSF.Util;
 using NPOI.POIFS;
 using NPOI.Util;  
 namespace SNF.Utilities
 {
     public class NPOIHelper
     {
         /// <summary>
         /// DataTable匯出到Excel檔案
         /// </summary>
         /// <param name="dtSource">源DataTable</param>
         /// <param name="strHeaderText">表頭文字</param>
         /// <param name="strFileName">儲存位置</param>
         public static void Export(DataTable dtSource, string strHeaderText, string strFileName)
         {
             using (MemoryStream ms = Export(dtSource, strHeaderText))
             {
                 using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
                 {
                     byte[] data = ms.ToArray();
                     fs.Write(data, 0, data.Length);
                     fs.Flush();
                 }
             }
         }
 
         /// <summary>
         /// DataTable匯出到Excel的MemoryStream
         /// </summary>
         /// <param name="dtSource">源DataTable</param>
         /// <param name="strHeaderText">表頭文字</param>
         public static MemoryStream Export(DataTable dtSource, string strHeaderText)
         {
             HSSFWorkbook workbook = new HSSFWorkbook();
             HSSFSheet sheet = workbook.CreateSheet();
 
             #region 右擊檔案 屬性資訊
             {
                 DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                 dsi.Company = "NPOI";
                 workbook.DocumentSummaryInformation = dsi;
 
                 SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                 si.Author = "檔案作者資訊"; //填加xls檔案作者資訊
                 si.ApplicationName = "建立程式資訊"; //填加xls檔案建立程式資訊
                 si.LastAuthor = "最後儲存者資訊"; //填加xls檔案最後儲存者資訊
                 si.Comments = "作者資訊"; //填加xls檔案作者資訊
                 si.Title = "標題資訊"; //填加xls檔案標題資訊

                 si.Subject = "主題資訊";//填加檔案主題資訊
                 si.CreateDateTime = DateTime.Now;
                 workbook.SummaryInformation = si;
             }
             #endregion
 
             HSSFCellStyle dateStyle = workbook.CreateCellStyle();
             HSSFDataFormat format = workbook.CreateDataFormat();
             dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
 
             //取得列寬
             int[] arrColWidth = new int[dtSource.Columns.Count];
             foreach (DataColumn item in dtSource.Columns)
             {
                 arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
             }
             for (int i = 0; i < dtSource.Rows.Count; i++)
             {
                 for (int j = 0; j < dtSource.Columns.Count; j++)
                 {
                     int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
                     if (intTemp > arrColWidth[j])
                     {
                         arrColWidth[j] = intTemp;
                     }
                 }
             } 
             int rowIndex = 0; 
             foreach (DataRow row in dtSource.Rows)
             {
                 #region 新建表,填充表頭,填充列頭,樣式
                 if (rowIndex == 65535 || rowIndex == 0)
                 {
                     if (rowIndex != 0)
                     {
                         sheet = workbook.CreateSheet();
                     }
 
                     #region 表頭及樣式
                     {
                         HSSFRow headerRow = sheet.CreateRow(0);
                         headerRow.HeightInPoints = 25;
                         headerRow.CreateCell(0).SetCellValue(strHeaderText);
 
                         HSSFCellStyle headStyle = workbook.CreateCellStyle();
                         headStyle.Alignment = CellHorizontalAlignment.CENTER;
                         HSSFFont font = workbook.CreateFont();
                         font.FontHeightInPoints = 20;
                         font.Boldweight = 700;
                         headStyle.SetFont(font);
                         headerRow.GetCell(0).CellStyle = headStyle;
                         sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
                         headerRow.Dispose();
                     }
                     #endregion
 
 
                     #region 列頭及樣式
                     {
                         HSSFRow headerRow = sheet.CreateRow(1); 
                         HSSFCellStyle headStyle = workbook.CreateCellStyle();
                         headStyle.Alignment = CellHorizontalAlignment.CENTER;
                         HSSFFont font = workbook.CreateFont();
                         font.FontHeightInPoints = 10;
                         font.Boldweight = 700;
                         headStyle.SetFont(font); 
                         foreach (DataColumn column in dtSource.Columns)
                         {
                             headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                             headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
 
                             //設定列寬
                             sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); 
                         }
                         headerRow.Dispose();
                     }
                     #endregion
 
                     rowIndex = 2;
                 }
                 #endregion
 
 
                 #region 填充內容
                 HSSFRow dataRow = sheet.CreateRow(rowIndex);
                 foreach (DataColumn column in dtSource.Columns)
                 {
                     HSSFCell newCell = dataRow.CreateCell(column.Ordinal);
 
                     string drValue = row[column].ToString();
 
                     switch (column.DataType.ToString())
                     {
                         case "System.String"://字串型別
                             newCell.SetCellValue(drValue);
                             break;
                         case "System.DateTime"://日期型別
                             DateTime dateV;
                             DateTime.TryParse(drValue, out dateV);
                             newCell.SetCellValue(dateV);
 
                             newCell.CellStyle = dateStyle;//格式化顯示
                             break;
                         case "System.Boolean"://布林型
                             bool boolV = false;
                             bool.TryParse(drValue, out boolV);
                             newCell.SetCellValue(boolV);
                             break;
                         case "System.Int16"://整型
                         case "System.Int32":
                         case "System.Int64":
                         case "System.Byte":
                             int intV = 0;
                             int.TryParse(drValue, out intV);
                             newCell.SetCellValue(intV);
                             break;
                         case "System.Decimal"://浮點型
                         case "System.Double":
                             double doubV = 0;
                             double.TryParse(drValue, out doubV);
                             newCell.SetCellValue(doubV);
                             break;
                         case "System.DBNull"://空值處理
                             newCell.SetCellValue("");
                             break;
                         default:
                             newCell.SetCellValue("");
                             break;
                     }
 
                 }
                 #endregion
 
                 rowIndex++;
             } 
             using (MemoryStream ms = new MemoryStream())
             {
                 workbook.Write(ms);
                 ms.Flush();
                 ms.Position = 0;
 
                 sheet.Dispose();
                 //workbook.Dispose();//一般只用寫這一個就OK了,他會遍歷並釋放所有資源,但當前版本有問題所以只釋放sheet
                 return ms;
             } 
         }
 
         /// <summary>
         /// 用於Web匯出
         /// </summary>
         /// <param name="dtSource">源DataTable</param>
         /// <param name="strHeaderText">表頭文字</param>
         /// <param name="strFileName">檔名</param>
         public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName)
         { 
             HttpContext curContext = HttpContext.Current;
 
             // 設定編碼和附件格式
             curContext.Response.ContentType = "application/vnd.ms-excel";
             curContext.Response.ContentEncoding = Encoding.UTF8;
             curContext.Response.Charset = "";
             curContext.Response.AppendHeader("Content-Disposition",
                 "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
 
             curContext.Response.BinaryWrite(Export(dtSource, strHeaderText).GetBuffer());
             curContext.Response.End(); 
         } 
 
         /// <summary>讀取excel
         /// 預設第一行為標頭
         /// </summary>
         /// <param name="strFileName">excel文件路徑</param>
         /// <returns></returns>
         public static DataTable Import(string strFileName)
         {
             DataTable dt = new DataTable();
 
             HSSFWorkbook hssfworkbook;
             using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
             {
                 hssfworkbook = new HSSFWorkbook(file);
             }
             HSSFSheet sheet = hssfworkbook.GetSheetAt(0);
             System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
 
             HSSFRow headerRow = sheet.GetRow(0);
             int cellCount = headerRow.LastCellNum;
 
             for (int j = 0; j < cellCount; j++)
             {
                 HSSFCell cell = headerRow.GetCell(j);
                 dt.Columns.Add(cell.ToString());
             }
 
             for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
             {
                 HSSFRow row = sheet.GetRow(i);
                 DataRow dataRow = dt.NewRow();
 
                 for (int j = row.FirstCellNum; j < cellCount; j++)
                 {
                     if (row.GetCell(j) != null)
                         dataRow[j] = row.GetCell(j).ToString();
                 }
 
                 dt.Rows.Add(dataRow);
             }
             return dt;
         }
     }
 }
複製程式碼

五、NPOI操作類的呼叫方法  

   DataTable dt_Grade = Tools.Data.GetDataTable(strSQL);
   filename += "績效考核結果分數統計表";
   PMS.Common.NPOIHelper.ExportByWeb(dt_Grade, filename, filename+".xls");

六、效果展示  

 

七、NPOI類庫下載:

資訊來源:http://www.cnblogs.com/yongfa365/archive/2010/05/10/NPOI-MyXls-DataTable-To-Excel-From-Excel.html

八、參考地址:

九、總結:

  通過以上分析,我們不難發現,用NPOI或MyXls代替是Excel是很明智的,在發文前,我看到NPOI及MyXls仍然在活躍的更新中。在使用過程中發現這兩個元件極相似,以前看過文章說他們使用的核心是一樣的。還有NPOI是國人開發的,且有相關中文文件,在很多地方有相關引用,下載量也很大。並且它支援Excel,看到MyXls相關問題基本上沒人回答,所以推薦使用NPOI。MyXls可以直接Cell.Font.Bold操作,而NPOI得使用CellType多少感覺有點麻煩。