今天上班不是很忙,考虑到经常有人要对 Excel 数据的读写操作,就花了一点功夫,把这部分写成一个模板,以便以后使用。虽然不难,但整理出来感觉还不错,就共享出来供大家参考和学习。

  1. /// Function: Read and write excel file  
  2. /// Author: Andy Niu  
  3. /// Date: 2011-12-08  
  4. using System;  
  5. using System.Data;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using Microsoft.Office.Interop.Excel;  
  9.  
  10. namespace MyClass  
  11. {  
  12.     public class MyExcel : IDisposable  
  13.     {  
  14.         private static readonly object missing = System.Reflection.Missing.Value;  
  15.         private ApplicationClass myExcel = new ApplicationClass();  
  16.  
  17.         #region Members  
  18.         private object updateLinks = missing;  
  19.         private object readOnly = missing;  
  20.         private object format = missing;  
  21.         private object password = missing;  
  22.         private object writeResPassword = missing;  
  23.         private object ignoreReadOnlyRecommended = missing;  
  24.         private object origin = missing;  
  25.         private object delimiter = missing;  
  26.         private object editable = missing;  
  27.         private object notify = missing;  
  28.         private object converter = missing;  
  29.         private object addToMru = missing;  
  30.         private object local = missing;  
  31.         private object corruptLoad = missing;  
  32.         private object conflictResolution = missing;  
  33.         private object textCodepage = missing;  
  34.         private object textVisualLayout = missing;  
  35.         private object readOnlyRecommended = missing;  
  36.         private object createBackup = missing;  
  37.  
  38.         private XlSaveAsAccessMode accessMode = XlSaveAsAccessMode.xlNoChange;  
  39.         private Style titleStyle = null;  
  40.         #endregion  
  41.  
  42.         #region Property  
  43.         public object UpdateLinks  
  44.         {  
  45.             get { return updateLinks; }  
  46.             set { updateLinks = value; }  
  47.         }  
  48.  
  49.         public object ReadOnly  
  50.         {  
  51.             get { return readOnly; }  
  52.             set { readOnly = value; }  
  53.         }  
  54.  
  55.         public object Format  
  56.         {  
  57.             get { return format; }  
  58.             set { format = value; }  
  59.         }  
  60.  
  61.         public object Password  
  62.         {  
  63.             get { return password; }  
  64.             set { password = value; }  
  65.         }  
  66.  
  67.         public object WriteResPassword  
  68.         {  
  69.             get { return writeResPassword; }  
  70.             set { writeResPassword = value; }  
  71.         }  
  72.  
  73.         public object IgnoreReadOnlyRecommended  
  74.         {  
  75.             get { return ignoreReadOnlyRecommended; }  
  76.             set { ignoreReadOnlyRecommended = value; }  
  77.         }  
  78.  
  79.         public object Origin  
  80.         {  
  81.             get { return origin; }  
  82.             set { origin = value; }  
  83.         }  
  84.  
  85.         public object Delimiter  
  86.         {  
  87.             get { return delimiter; }  
  88.             set { delimiter = value; }  
  89.         }  
  90.  
  91.         public object Editable  
  92.         {  
  93.             get { return editable; }  
  94.             set { editable = value; }  
  95.         }  
  96.  
  97.         public object Notify  
  98.         {  
  99.             get { return notify; }  
  100.             set { notify = value; }  
  101.         }  
  102.  
  103.         public object Converter  
  104.         {  
  105.             get { return converter; }  
  106.             set { converter = value; }  
  107.         }  
  108.  
  109.         public object AddToMru  
  110.         {  
  111.             get { return addToMru; }  
  112.             set { addToMru = value; }  
  113.         }  
  114.  
  115.         public object Local  
  116.         {  
  117.             get { return local; }  
  118.             set { local = value; }  
  119.         }  
  120.  
  121.         public object CorruptLoad  
  122.         {  
  123.             get { return corruptLoad; }  
  124.             set { corruptLoad = value; }  
  125.         }  
  126.  
  127.         public object ConflictResolution  
  128.         {  
  129.             get { return conflictResolution; }  
  130.             set { conflictResolution = value; }  
  131.         }  
  132.  
  133.         public object TextCodepage  
  134.         {  
  135.             get { return textCodepage; }  
  136.             set { textCodepage = value; }  
  137.         }  
  138.  
  139.         public object TextVisualLayout  
  140.         {  
  141.             get { return textVisualLayout; }  
  142.             set { textVisualLayout = value; }  
  143.         }  
  144.  
  145.         public object ReadOnlyRecommended  
  146.         {  
  147.             get { return readOnlyRecommended; }  
  148.             set { readOnlyRecommended = value; }  
  149.         }  
  150.  
  151.         public object CreateBackup  
  152.         {  
  153.             get { return createBackup; }  
  154.             set { createBackup = value; }  
  155.         }  
  156.  
  157.         public XlSaveAsAccessMode AccessMode  
  158.         {  
  159.             get { return accessMode; }  
  160.             set { accessMode = value; }  
  161.         }  
  162.  
  163.         public Style TitleStyle  
  164.         {  
  165.             get { return titleStyle; }  
  166.             set { titleStyle = value; }  
  167.         }  
  168.  
  169.         #endregion  
  170.  
  171.         #region Column Name  
  172.         private static readonly string[] titles = new string[] { "Z""A""B""C""D""E""F""G""H""I""J""K""L""M""N""O""P""Q""R""S""T""U""V""W""X""Y" };  
  173.         private string columnName(int colIndex)  
  174.         {  
  175.             if (colIndex < 0)  
  176.             {  
  177.                 throw new Exception("Column Index Error");  
  178.             }  
  179.  
  180.             string colName = string.Empty;  
  181.             // 十進制轉化為26進制  
  182.             int reminder = colIndex % 26;  
  183.             while (colIndex != 0)  
  184.             {  
  185.                 colName = string.Format("{0}{1}", titles[reminder], colName);  
  186.                 colIndex = colIndex / 26;  
  187.                 reminder = colIndex % 26;  
  188.             }  
  189.             return colName;  
  190.         }  
  191.         #endregion  
  192.  
  193.         #region Public Method  
  194.         /// <summary>  
  195.         /// Oepn Excel File  
  196.         /// </summary>  
  197.         /// <param name="fileName">the fullpath of excel file </param>  
  198.         /// <returns>return a instance of workbook</returns>  
  199.         public Workbook Open(string fileName)  
  200.         {  
  201.             if (myExcel == null)  
  202.             {  
  203.                 throw new Exception("Application Error : myExcel is null");  
  204.             }  
  205.  
  206.             if (string.IsNullOrEmpty(fileName))  
  207.             {  
  208.                 throw new Exception("Parameter is empty or null");  
  209.             }  
  210.             try 
  211.             {  
  212.                 return myExcel.Application.Workbooks.Open(fileName, updateLinks, readOnly, format, password, writeResPassword, ignoreReadOnlyRecommended, origin, delimiter, editable, notify, converter, addToMru, local, corruptLoad);  
  213.             }  
  214.             catch (Exception ex)  
  215.             {  
  216.                 throw ex;  
  217.             }  
  218.         }  
  219.         /// <summary>  
  220.         /// Get data from sheet of wookbook.  
  221.         /// </summary>  
  222.         /// <param name="sheet">a instance of wooksheet .</param>  
  223.         /// <param name="isContainsTitle">a mark means that sheet whether contains title or not .</param>  
  224.         /// <returns>ratrun a dataset</returns>  
  225.         public DataSet GetDataSet(Worksheet sheet, bool isContainsTitle)  
  226.         {  
  227.             if (sheet == null)  
  228.             {  
  229.                 throw new Exception("Parameter sheet  is null ");  
  230.             }  
  231.             DataSet ds = new DataSet(sheet.Name);  
  232.             try 
  233.             {  
  234.                 // 起始行数  
  235.                 int startRow = 1;  
  236.                 if (!isContainsTitle)  
  237.                 {  
  238.                     startRow = 0;  
  239.                 }  
  240.                 // 起始列数  
  241.                 int startCol = 1;  
  242.  
  243.                 // 总行數(若有標題,則包括标题)  
  244.                 int rowCount = sheet.UsedRange.Cells.Rows.Count;  
  245.                 // 总列数  
  246.                 int columnCount = sheet.UsedRange.Cells.Columns.Count;  
  247.                 // 获取记录值  
  248.                 object[,] value = (object[,])sheet.UsedRange.Value2;  
  249.                 // 新添 Table  
  250.                 System.Data.DataTable table = new System.Data.DataTable(sheet.Name); ;  
  251.                 ds.Tables.Add(table);  
  252.  
  253.                 // 添加标题  
  254.                 if (isContainsTitle)  
  255.                 {  
  256.                     for (int i = startCol; i <= columnCount; i++)  
  257.                     {  
  258.                         if (value[startRow, i] == null)  
  259.                         {  
  260.                             throw new Exception("Excel read error : Excel contains empty header columns ");  
  261.                         }  
  262.                         table.Columns.Add(value[startRow, i].ToString());  
  263.                     }  
  264.                 }  
  265.                 else 
  266.                 {  
  267.                     for (int i = startCol; i <= columnCount; i++)  
  268.                     {  
  269.                         table.Columns.Add(columnName(i)); ;  
  270.                     }  
  271.                 }  
  272.  
  273.                 // 添加数据  
  274.                 for (int i = startRow + 1; i < rowCount; i++)  
  275.                 {  
  276.                     DataRow row = table.NewRow();  
  277.                     for (int j = startCol; j < columnCount; j++)  
  278.                     {  
  279.                         row[j - startCol] = value[i, j];  
  280.                     }  
  281.                     table.Rows.Add(row);  
  282.                 }  
  283.             }  
  284.             catch (Exception ex)  
  285.             {  
  286.                 throw ex;  
  287.             }  
  288.             return ds;  
  289.         }  
  290.         /// <summary>  
  291.         /// Write the first table data of dataset to excel file  
  292.         /// </summary>  
  293.         /// <param name="data">a instance of dataset</param>  
  294.         /// <param name="fileName">special the file path with saving excel file</param>  
  295.         public void WriteToExcel(DataSet data, string fileName)  
  296.         {  
  297.             if (data == null)  
  298.             {  
  299.                 throw new Exception("Parameter data can not be empty");  
  300.             }  
  301.             // 数据表  
  302.             System.Data.DataTable table = data.Tables[0];  
  303.             // 添加工作簿  
  304.             myExcel.Application.Workbooks.Add(true);  
  305.             // 总列数  
  306.             int columnCount = table.Columns.Count;  
  307.             // 总行数 不包括标题  
  308.             int rowCount = table.Rows.Count;  
  309.             // 起始行号  
  310.             const int startRow = 2;  
  311.             // 起始列号  
  312.             const int startCol = 1;  
  313.             // 标题行号  
  314.             const int titleRowIndex = 1;  
  315.             // excel 数据域  
  316.             Range excelData = myExcel.Cells;  
  317.             // 写标题  
  318.             for (int colIndex = startCol; colIndex < columnCount; colIndex++)  
  319.             {  
  320.                 excelData[titleRowIndex, colIndex] = table.Columns[colIndex - 1].ColumnName;  
  321.             }  
  322.             // 写数据  
  323.             for (int rowIndex = 0; rowIndex < rowCount - 1; rowIndex++)  
  324.             {  
  325.                 DataRow row = table.Rows[rowIndex];  
  326.                 for (int colIndex = startCol; colIndex < columnCount; colIndex++)  
  327.                 {  
  328.                     if (row[colIndex - 1] == null)  
  329.                     {  
  330.                         continue;  
  331.                     }  
  332.                     excelData[rowIndex + startRow, colIndex] = row[colIndex - 1].ToString();  
  333.                 }  
  334.             }  
  335.  
  336.             // 设置Title样式  
  337.             if (SetTitleStyle != null)  
  338.             {  
  339.                 SetTitleStyle(thisnew EventArgs());  
  340.                 Range title = excelData.get_Range(string.Format("{0}{1}", columnName(startCol), titleRowIndex), string.Format("{0}{1}", columnName(columnCount), titleRowIndex));  
  341.                 if (titleStyle != null)  
  342.                 {  
  343.                     title.Style = titleStyle;  
  344.                 }  
  345.             }  
  346.             // 自动调整列宽  
  347.             excelData.EntireColumn.AutoFit();  
  348.             // 自动调整行高  
  349.             excelData.EntireRow.AutoFit();  
  350.             // 设置文件格式  
  351.             Format = XlFileFormat.xlWorkbookNormal;  
  352.             ReadOnlyRecommended = false;  
  353.             CreateBackup = false;  
  354.             // 保存时,不弹出是否保存的窗口直接保存  
  355.             myExcel.DisplayAlerts = false;  
  356.             myExcel.ActiveWorkbook.SaveAs(fileName, format, password, writeResPassword, readOnlyRecommended, createBackup, accessMode, conflictResolution, addToMru, textCodepage, textVisualLayout, local);  
  357.             myExcel.ActiveWorkbook.Close(false, fileName, false);  
  358.         }  
  359.  
  360.         public Microsoft.Office.Interop.Excel.Style AddStyle(string styleName)  
  361.         {  
  362.             if (string.IsNullOrEmpty(styleName))  
  363.             {  
  364.                 throw new Exception("The style name is empty ");  
  365.             }  
  366.             return myExcel.Application.ActiveWorkbook.Styles.Add(styleName, missing);  
  367.         }  
  368.         #endregion  
  369.  
  370.         #region Event  
  371.         public delegate void SetTitleStyleHandler(object sender, EventArgs e);  
  372.         public event SetTitleStyleHandler SetTitleStyle;  
  373.         #endregion  
  374.  
  375.         #region Implemented IDisposable Member  
  376.         public void Dispose()  
  377.         {  
  378.             if (myExcel != null)  
  379.             {  
  380.                 myExcel.DisplayAlerts = false;  
  381.                 if (myExcel.Application.ActiveWorkbook != null)  
  382.                 {  
  383.                     myExcel.Application.ActiveWorkbook.Close(falsenullfalse);  
  384.                 }  
  385.                 myExcel.Quit();  
  386.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);  
  387.                 myExcel = null;  
  388.                 GC.Collect();  
  389.             }  
  390.         }  
  391.         #endregion  
  392.     }