NPOI、MyXls、Aspose.Cells 導入導出Excel


Excel導入及導出問題產生:

  從接觸.net到現在一直在維護一個DataTable導s出到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 || Aspose.Cells == 研究幾年Excel。

  NPOI開源地址:http://npoi.codeplex.com/
NPOI中文文檔:http://www.cnblogs.com/tonyqus/archive/2009/04/12/1434209.html

  MyXls開源地址:http://sourceforge.net/projects/myxls/

     Aspose.Cells是個商業軟件,下載地址:http://www.evget.com/zh-CN/product/563/feature_en.aspx

下面來兩個簡單入門例子:
MyXls 快速入門例子:

  1. /// <summary>
  2. /// MyXls簡單Demo,快速入門代碼
  3. /// </summary>
  4. /// <param name="dtSource"></param>
  5. /// <param name="strFileName"></param>
  6. /// <remarks>MyXls認為Excel的第一個單元格是:(1,1)</remarks>
  7. /// <Author>柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41</Author>
  8. publicstaticvoid ExportEasy(DataTable dtSource, string strFileName)
  9. {
  10. XlsDocument xls = new XlsDocument();
  11. Worksheet sheet = xls.Workbook.Worksheets.Add("Sheet1");
  12. //填充表頭
  13. foreach (DataColumn col in dtSource.Columns)
  14. {
  15. sheet.Cells.Add(1, col.Ordinal + 1, col.ColumnName);
  16. }
  17. //填充內容
  18. for (int i = 0; i < dtSource.Rows.Count; i++)
  19. {
  20. for (int j = 0; j < dtSource.Columns.Count; j++)
  21. {
  22. sheet.Cells.Add(i + 2, j + 1, dtSource.Rows[i][j].ToString());
  23. }
  24. }
  25. //保存
  26. xls.FileName = strFileName;
  27. xls.Save();
  28. }
/// <summary>
/// MyXls簡單Demo,快速入門代碼
/// </summary>
/// <param name="dtSource"></param>
/// <param name="strFileName"></param>
/// <remarks>MyXls認為Excel的第一個單元格是:(1,1)</remarks>
/// <Author>柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41</Author>
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 快速入門例子:

  1. /// <summary>
  2. /// NPOI簡單Demo,快速入門代碼
  3. /// </summary>
  4. /// <param name="dtSource"></param>
  5. /// <param name="strFileName"></param>
  6. /// <remarks>NPOI認為Excel的第一個單元格是:(0,0)</remarks>
  7. /// <Author>柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41</Author>
  8. publicstaticvoid ExportEasy(DataTable dtSource, string strFileName)
  9. {
  10. HSSFWorkbook workbook = new HSSFWorkbook();
  11. HSSFSheet sheet = workbook.CreateSheet();
  12. //填充表頭
  13. HSSFRow dataRow = sheet.CreateRow(0);
  14. foreach (DataColumn column in dtSource.Columns)
  15. {
  16. dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
  17. }
  18. //填充內容
  19. for (int i = 0; i < dtSource.Rows.Count; i++)
  20. {
  21. dataRow = sheet.CreateRow(i + 1);
  22. for (int j = 0; j < dtSource.Columns.Count; j++)
  23. {
  24. dataRow.CreateCell(j).SetCellValue(dtSource.Rows[i][j].ToString());
  25. }
  26. }
  27. //保存
  28. using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
  29. {
  30. workbook.Write(fs);
  31. }
  32. workbook.Dispose();
  33. }
/// <summary>
/// NPOI簡單Demo,快速入門代碼
/// </summary>
/// <param name="dtSource"></param>
/// <param name="strFileName"></param>
/// <remarks>NPOI認為Excel的第一個單元格是:(0,0)</remarks>
/// <Author>柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41</Author>
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 (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
    {
        workbook.Write(fs);
    }
    workbook.Dispose();
}

接下來是柳永法(yongfa365)'Blog封裝的可以用在實際項目中的類,實現的功能有(僅NPOI):

  1. 支持web及winform從DataTable導出到Excel。
  2. 生成速度很快。
  3. 准確判斷數據類型,不會出現身份證轉數值等上面提到的一系列問題。
  4. 如果單頁條數大於65535時會新建工作表。
  5. 列寬自適應。
  6. 支持讀取Excel。
  7. 調用方便,只一調用一個靜態類就OK了。

因為測試期間發現MyXls導出速度要比NPOI慢3倍,而NPOI既能滿足我們的導出需求,又能很好的滿足我們的導入需求,所以只針對NPOI進行全方位功能實現及優化。

MyXls導出相關類:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using org.in2bits.MyXls;
  6. using org.in2bits.MyXls.ByteUtil;
  7. using System.Data;
  8. class ExcelHelper
  9. {
  10. publicstaticvoid Export(DataTable dtSource, string strHeaderText, string strFileName)
  11. {
  12. XlsDocument xls = new XlsDocument();
  13. xls.FileName = DateTime.Now.ToString("yyyyMMddHHmmssffff", System.Globalization.DateTimeFormatInfo.InvariantInfo);
  14. xls.SummaryInformation.Author = "yongfa365"; //填加xls文件作者信息
  15. xls.SummaryInformation.NameOfCreatingApplication = "liu yongfa"; //填加xls文件創建程序信息
  16. xls.SummaryInformation.LastSavedBy = "LastSavedBy"; //填加xls文件最后保存者信息
  17. xls.SummaryInformation.Comments = "Comments"; //填加xls文件作者信息
  18. xls.SummaryInformation.Title = "title"; //填加xls文件標題信息
  19. xls.SummaryInformation.Subject = "Subject";//填加文件主題信息
  20. xls.DocumentSummaryInformation.Company = "company";//填加文件公司信息
  21. Worksheet sheet = xls.Workbook.Worksheets.Add("Sheet1");//狀態欄標題名稱
  22. Cells cells = sheet.Cells;
  23. foreach (DataColumn col in dtSource.Columns)
  24. {
  25. Cell cell = cells.Add(1, col.Ordinal + 1, col.ColumnName);
  26. cell.Font.FontFamily = FontFamilies.Roman; //字體
  27. cell.Font.Bold = true; //字體為粗體
  28. }
  29. #region 填充內容
  30. XF dateStyle = xls.NewXF();
  31. dateStyle.Format = "yyyy-mm-dd";
  32. for (int i = 0; i < dtSource.Rows.Count; i++)
  33. {
  34. for (int j = 0; j < dtSource.Columns.Count; j++)
  35. {
  36. int rowIndex = i + 2;
  37. int colIndex = j + 1;
  38. string drValue = dtSource.Rows[i][j].ToString();
  39. switch (dtSource.Rows[i][j].GetType().ToString())
  40. {
  41. case"System.String"://字符串類型
  42. cells.Add(rowIndex, colIndex, drValue);
  43. break;
  44. case"System.DateTime"://日期類型
  45. DateTime dateV;
  46. DateTime.TryParse(drValue, out dateV);
  47. cells.Add(rowIndex, colIndex, dateV, dateStyle);
  48. break;
  49. case"System.Boolean"://布爾型
  50. bool boolV = false;
  51. bool.TryParse(drValue, out boolV);
  52. cells.Add(rowIndex, colIndex, boolV);
  53. break;
  54. case"System.Int16"://整型
  55. case"System.Int32":
  56. case"System.Int64":
  57. case"System.Byte":
  58. int intV = 0;
  59. int.TryParse(drValue, out intV);
  60. cells.Add(rowIndex, colIndex, intV);
  61. break;
  62. case"System.Decimal"://浮點型
  63. case"System.Double":
  64. double doubV = 0;
  65. double.TryParse(drValue, out doubV);
  66. cells.Add(rowIndex, colIndex, doubV);
  67. break;
  68. case"System.DBNull"://空值處理
  69. cells.Add(rowIndex, colIndex, null);
  70. break;
  71. default:
  72. cells.Add(rowIndex, colIndex, null);
  73. break;
  74. }
  75. }
  76. }
  77. #endregion
  78. xls.FileName = strFileName;
  79. xls.Save();
  80. }
  81. }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using org.in2bits.MyXls;
using org.in2bits.MyXls.ByteUtil;
using System.Data;

class ExcelHelper
{
    public static void Export(DataTable dtSource, string strHeaderText, string strFileName)
    {
        XlsDocument xls = new XlsDocument();
        xls.FileName = DateTime.Now.ToString("yyyyMMddHHmmssffff", System.Globalization.DateTimeFormatInfo.InvariantInfo);
        xls.SummaryInformation.Author = "yongfa365"; //填加xls文件作者信息
        xls.SummaryInformation.NameOfCreatingApplication = "liu yongfa"; //填加xls文件創建程序信息
        xls.SummaryInformation.LastSavedBy = "LastSavedBy"; //填加xls文件最后保存者信息
        xls.SummaryInformation.Comments = "Comments"; //填加xls文件作者信息
        xls.SummaryInformation.Title = "title"; //填加xls文件標題信息
        xls.SummaryInformation.Subject = "Subject";//填加文件主題信息
        xls.DocumentSummaryInformation.Company = "company";//填加文件公司信息


        Worksheet sheet = xls.Workbook.Worksheets.Add("Sheet1");//狀態欄標題名稱
        Cells cells = sheet.Cells;

        foreach (DataColumn col in dtSource.Columns)
        {
            Cell cell = cells.Add(1, col.Ordinal + 1, col.ColumnName);
            cell.Font.FontFamily = FontFamilies.Roman; //字體
            cell.Font.Bold = true;  //字體為粗體  

        }
        #region 填充內容
        XF dateStyle = xls.NewXF();
        dateStyle.Format = "yyyy-mm-dd";

        for (int i = 0; i < dtSource.Rows.Count; i++)
        {
            for (int j = 0; j < dtSource.Columns.Count; j++)
            {

                int rowIndex = i + 2;
                int colIndex = j + 1;
                string drValue = dtSource.Rows[i][j].ToString();

                switch (dtSource.Rows[i][j].GetType().ToString())
                {
                    case "System.String"://字符串類型
                        cells.Add(rowIndex, colIndex, drValue);
                        break;
                    case "System.DateTime"://日期類型
                        DateTime dateV;
                        DateTime.TryParse(drValue, out dateV);
                        cells.Add(rowIndex, colIndex, dateV, dateStyle);
                        break;
                    case "System.Boolean"://布爾型
                        bool boolV = false;
                        bool.TryParse(drValue, out boolV);
                        cells.Add(rowIndex, colIndex, boolV);
                        break;
                    case "System.Int16"://整型
                    case "System.Int32":
                    case "System.Int64":
                    case "System.Byte":
                        int intV = 0;
                        int.TryParse(drValue, out intV);
                        cells.Add(rowIndex, colIndex, intV);
                        break;
                    case "System.Decimal"://浮點型
                    case "System.Double":
                        double doubV = 0;
                        double.TryParse(drValue, out doubV);
                        cells.Add(rowIndex, colIndex, doubV);
                        break;
                    case "System.DBNull"://空值處理
                        cells.Add(rowIndex, colIndex, null);
                        break;
                    default:
                        cells.Add(rowIndex, colIndex, null);
                        break;
                }
            }
        }

        #endregion

        xls.FileName = strFileName;
        xls.Save();
    }
}

NPOI導入導出相關類:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.IO;
  5. using System.Text;
  6. using System.Web;
  7. using NPOI;
  8. using NPOI.HPSF;
  9. using NPOI.HSSF;
  10. using NPOI.HSSF.UserModel;
  11. using NPOI.HSSF.Util;
  12. using NPOI.POIFS;
  13. using NPOI.Util;
  14. publicclass ExcelHelper
  15. {
  16. /// <summary>
  17. /// DataTable導出到Excel文件
  18. /// </summary>
  19. /// <param name="dtSource">源DataTable</param>
  20. /// <param name="strHeaderText">表頭文本</param>
  21. /// <param name="strFileName">保存位置</param>
  22. /// <Author>柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41</Author>
  23. publicstaticvoid Export(DataTable dtSource, string strHeaderText, string strFileName)
  24. {
  25. using (MemoryStream ms = Export(dtSource, strHeaderText))
  26. {
  27. using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
  28. {
  29. byte[] data = ms.ToArray();
  30. fs.Write(data, 0, data.Length);
  31. fs.Flush();
  32. }
  33. }
  34. }
  35. /// <summary>
  36. /// DataTable導出到Excel的MemoryStream
  37. /// </summary>
  38. /// <param name="dtSource">源DataTable</param>
  39. /// <param name="strHeaderText">表頭文本</param>
  40. /// <Author>柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41</Author>
  41. publicstatic MemoryStream Export(DataTable dtSource, string strHeaderText)
  42. {
  43. HSSFWorkbook workbook = new HSSFWorkbook();
  44. HSSFSheet sheet = workbook.CreateSheet();
  45. #region 右擊文件 屬性信息
  46. {
  47. DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  48. dsi.Company = "http://www.yongfa365.com/";
  49. workbook.DocumentSummaryInformation = dsi;
  50. SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  51. si.Author = "柳永法"; //填加xls文件作者信息
  52. si.ApplicationName = "NPOI測試程序"; //填加xls文件創建程序信息
  53. si.LastAuthor = "柳永法2"; //填加xls文件最后保存者信息
  54. si.Comments = "說明信息"; //填加xls文件作者信息
  55. si.Title = "NPOI測試"; //填加xls文件標題信息
  56. si.Subject = "NPOI測試Demo";//填加文件主題信息
  57. si.CreateDateTime = DateTime.Now;
  58. workbook.SummaryInformation = si;
  59. }
  60. #endregion
  61. HSSFCellStyle dateStyle = workbook.CreateCellStyle();
  62. HSSFDataFormat format = workbook.CreateDataFormat();
  63. dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
  64. //取得列寬
  65. int[] arrColWidth = newint[dtSource.Columns.Count];
  66. foreach (DataColumn item in dtSource.Columns)
  67. {
  68. arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
  69. }
  70. for (int i = 0; i < dtSource.Rows.Count; i++)
  71. {
  72. for (int j = 0; j < dtSource.Columns.Count; j++)
  73. {
  74. int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
  75. if (intTemp > arrColWidth[j])
  76. {
  77. arrColWidth[j] = intTemp;
  78. }
  79. }
  80. }
  81. int rowIndex = 0;
  82. foreach (DataRow row in dtSource.Rows)
  83. {
  84. #region 新建表,填充表頭,填充列頭,樣式
  85. if (rowIndex == 65535 || rowIndex == 0)
  86. {
  87. if (rowIndex != 0)
  88. {
  89. sheet = workbook.CreateSheet();
  90. }
  91. #region 表頭及樣式
  92. {
  93. HSSFRow headerRow = sheet.CreateRow(0);
  94. headerRow.HeightInPoints = 25;
  95. headerRow.CreateCell(0).SetCellValue(strHeaderText);
  96. HSSFCellStyle headStyle = workbook.CreateCellStyle();
  97. headStyle.Alignment = CellHorizontalAlignment.CENTER;
  98. HSSFFont font = workbook.CreateFont();
  99. font.FontHeightInPoints = 20;
  100. font.Boldweight = 700;
  101. headStyle.SetFont(font);
  102. headerRow.GetCell(0).CellStyle = headStyle;
  103. sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
  104. headerRow.Dispose();
  105. }
  106. #endregion
  107. #region 列頭及樣式
  108. {
  109. HSSFRow headerRow = sheet.CreateRow(1);
  110. HSSFCellStyle headStyle = workbook.CreateCellStyle();
  111. headStyle.Alignment = CellHorizontalAlignment.CENTER;
  112. HSSFFont font = workbook.CreateFont();
  113. font.FontHeightInPoints = 10;
  114. font.Boldweight = 700;
  115. headStyle.SetFont(font);
  116. foreach (DataColumn column in dtSource.Columns)
  117. {
  118. headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
  119. headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
  120. //設置列寬
  121. sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
  122. }
  123. headerRow.Dispose();
  124. }
  125. #endregion
  126. rowIndex = 2;
  127. }
  128. #endregion
  129. #region 填充內容
  130. HSSFRow dataRow = sheet.CreateRow(rowIndex);
  131. foreach (DataColumn column in dtSource.Columns)
  132. {
  133. HSSFCell newCell = dataRow.CreateCell(column.Ordinal);
  134. string drValue = row[column].ToString();
  135. switch (column.DataType.ToString())
  136. {
  137. case"System.String"://字符串類型
  138. newCell.SetCellValue(drValue);
  139. break;
  140. case"System.DateTime"://日期類型
  141. DateTime dateV;
  142. DateTime.TryParse(drValue, out dateV);
  143. newCell.SetCellValue(dateV);
  144. newCell.CellStyle = dateStyle;//格式化顯示
  145. break;
  146. case"System.Boolean"://布爾型
  147. bool boolV = false;
  148. bool.TryParse(drValue, out boolV);
  149. newCell.SetCellValue(boolV);
  150. break;
  151. case"System.Int16"://整型
  152. case"System.Int32":
  153. case"System.Int64":
  154. case"System.Byte":
  155. int intV = 0;
  156. int.TryParse(drValue, out intV);
  157. newCell.SetCellValue(intV);
  158. break;
  159. case"System.Decimal"://浮點型
  160. case"System.Double":
  161. double doubV = 0;
  162. double.TryParse(drValue, out doubV);
  163. newCell.SetCellValue(doubV);
  164. break;
  165. case"System.DBNull"://空值處理
  166. newCell.SetCellValue("");
  167. break;
  168. default:
  169. newCell.SetCellValue("");
  170. break;
  171. }
  172. }
  173. #endregion
  174. rowIndex++;
  175. }
  176. using (MemoryStream ms = new MemoryStream())
  177. {
  178. workbook.Write(ms);
  179. ms.Flush();
  180. ms.Position = 0;
  181. sheet.Dispose();
  182. //workbook.Dispose();//一般只用寫這一個就OK了,他會遍歷並釋放所有資源,但當前版本有問題所以只釋放sheet
  183. return ms;
  184. }
  185. }
  186. /// <summary>
  187. /// 用於Web導出
  188. /// </summary>
  189. /// <param name="dtSource">源DataTable</param>
  190. /// <param name="strHeaderText">表頭文本</param>
  191. /// <param name="strFileName">文件名</param>
  192. /// <Author>柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41</Author>
  193. publicstaticvoid ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName)
  194. {
  195. HttpContext curContext = HttpContext.Current;
  196. // 設置編碼和附件格式
  197. curContext.Response.ContentType = "application/vnd.ms-excel";
  198. curContext.Response.ContentEncoding = Encoding.UTF8;
  199. curContext.Response.Charset = "";
  200. curContext.Response.AppendHeader("Content-Disposition",
  201. "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
  202. curContext.Response.BinaryWrite(Export(dtSource, strHeaderText).GetBuffer());
  203. curContext.Response.End();
  204. }
  205. /// <summary>讀取excel
  206. /// 默認第一行為標頭
  207. /// </summary>
  208. /// <param name="strFileName">excel文檔路徑</param>
  209. /// <returns></returns>
  210. publicstatic DataTable Import(string strFileName)
  211. {
  212. DataTable dt = new DataTable();
  213. HSSFWorkbook hssfworkbook;
  214. using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
  215. {
  216. hssfworkbook = new HSSFWorkbook(file);
  217. }
  218. HSSFSheet sheet = hssfworkbook.GetSheetAt(0);
  219. System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
  220. HSSFRow headerRow = sheet.GetRow(0);
  221. int cellCount = headerRow.LastCellNum;
  222. for (int j = 0; j < cellCount; j++)
  223. {
  224. HSSFCell cell = headerRow.GetCell(j);
  225. dt.Columns.Add(cell.ToString());
  226. }
  227. for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
  228. {
  229. HSSFRow row = sheet.GetRow(i);
  230. DataRow dataRow = dt.NewRow();
  231. for (int j = row.FirstCellNum; j < cellCount; j++)
  232. {
  233. if (row.GetCell(j) != null)
  234. dataRow[j] = row.GetCell(j).ToString();
  235. }
  236. dt.Rows.Add(dataRow);
  237. }
  238. return dt;
  239. }
  240. }
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.POIFS;
using NPOI.Util;


public class ExcelHelper
{
    /// <summary>
    /// DataTable導出到Excel文件
    /// </summary>
    /// <param name="dtSource">源DataTable</param>
    /// <param name="strHeaderText">表頭文本</param>
    /// <param name="strFileName">保存位置</param>
    /// <Author>柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41</Author>
    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>
    /// <Author>柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41</Author>
    public static MemoryStream Export(DataTable dtSource, string strHeaderText)
    {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.CreateSheet();

        #region 右擊文件 屬性信息
        {
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "http://www.yongfa365.com/";
            workbook.DocumentSummaryInformation = dsi;

            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Author = "柳永法"; //填加xls文件作者信息
            si.ApplicationName = "NPOI測試程序"; //填加xls文件創建程序信息
            si.LastAuthor = "柳永法2"; //填加xls文件最后保存者信息
            si.Comments = "說明信息"; //填加xls文件作者信息
            si.Title = "NPOI測試"; //填加xls文件標題信息
            si.Subject = "NPOI測試Demo";//填加文件主題信息
            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>
    /// <Author>柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41</Author>
    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;
    }

}
Aspose.Cells 使用整理 
 

以上

這兩天用Aspose.Cells構建一個Excel報表,感覺這個組件還比較好用.記錄一下常用的使用知識:這兩天用Aspose.Cells構建一個Excel報表,感覺這個組件還比較好用.記錄一下常用的使用知識:

1.創建Workbook和Worksheet

workbook&worksheet1
Workbook wb = new Workbook();
wb.Worksheets.Clear();
wb.Worksheets.Add("New Worksheet1");//New Worksheet1是Worksheet的name
Worksheet ws = wb.Worksheets[0];
如果直接用下邊兩句則直接使用默認的第一個Worksheet:

workbook&worksheet2
Workbook wb = new Workbook();
Worksheet ws = wb.Worksheets[0];
2.給Cell賦值設置背景顏色並加背景色:

cell1
Cell cell = ws.Cells[0, 0];
cell.PutValue("填充"); //必須用PutValue方法賦值
cell.Style.ForegroundColor = Color.Yellow;
cell.Style.Pattern = BackgroundType.Solid;
cell.Style.Font.Size = 10;
cell.Style.Font.Color = Color.Blue;
自定義格式:

cell2
cell.Style.Custom = "ddd, dd mmmm 'yy";
旋轉字體:

cell3
cell.Style.Rotation = 90;
3.設置Range並賦值加Style

range1
int styleIndex = wb.Styles.Add();
Style style = wb.Styles[styleIndex];
style.ForegroundColor = Color.Yellow;
style.Pattern = BackgroundType.Solid;
style.Font.Size = 10;

//從Cells[0,0]開始創建一個2行3列的Range
Range range = ws.Cells.CreateRange(0, 0, 2, 3);
Cell cell = range[0, 0];
cell.Style.Font = 9;
range.Style = style;
range.Merge();
注意Range不能直接設置Style.必須先定義style再將style賦給Style.其他設置和Cell基本一致.Range的Style會覆蓋Cell定義的Style.另外必須先賦值再傳Style.否則可能不生效.

4.使用Formula:

formula1
ws.Cells[0,0].PutValue(1);
ws.Cells[1,0].PutValue(20);
ws.Cells[2,0].Formula="SUM(A1:B1)";
wb.CalculateFormula(true);
Save Excel文件的時候必須調用CalculateFormula方法計算結果.

5.插入圖片:

pictures1
string imageUrl = System.Web.HttpContext.Current.Server.MapPath("~/images/log_topleft.gif");
ws.Pictures.Add(10, 10, imageUrl);

6.使用Validations:

validations1
Cells cells = ws.Cells;

cells[12, 0].PutValue("Please enter a number other than 0 to 10 in B1 to activate data validation:");
cells[12, 0].Style.IsTextWrapped = true;

cells[12, 1].PutValue(5);
Validations validations = totalSheet.Validations;

Validation validation = validations[validations.Add()];
//Set the data validation type
validation.Type = ValidationType.WholeNumber;
//Set the operator for the data validation
validation.Operator = OperatorType.Between;
//Set the value or expression associated with the data validation
validation.Formula1 = "0";
//the value or expression associated with the second part of the data validation
validation.Formula2 = "10";

validation.ShowError = true;
//Set the validation alert style
validation.AlertStyle = ValidationAlertType.Information;
//Set the title of the data-validation error dialog box
validation.ErrorTitle = "Error";
//Set the data validation error message
validation.ErrorMessage = " Enter value between 0 to 10";
//Set the data validation input message
validation.InputMessage = "Data Validation using Condition for Numbers";
validation.IgnoreBlank = true;
validation.ShowInput = true;
validation.ShowError = true;

//設置Validations的區域,因為現在要Validations的位置是12,1,所以下面設置對應的也要是12,1
CellArea cellArea;
cellArea.StartRow = 12;
cellArea.EndRow = 12;
cellArea.StartColumn = 1;
cellArea.EndColumn = 1;
validation.AreaList.Add(cellArea);

/*
要注意 的地方Validations 也是和Range的Style一樣,要新增的,否則不生效
*/

相關源碼及測試用例下載地址:

http://download.csdn.net/source/2330821

參考地址:

NPOI導出Excel表功能實現(多個工作簿):http://www.cnblogs.com/zhengjuzhuan/archive/2010/02/01/1661103.html
在 Server 端存取 Excel 檔案的利器:NPOI Library:http://msdn.microsoft.com/zh-tw/ee818993.aspx
ASP.NET使用NPOI類庫導出Excel:http://www.cnblogs.com/niunan/archive/2010/03/30/1700706.html

總結:

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM