Excel操作 Microsoft.Office.Interop.Excel.dll的使用


先說說題外話,前段時間近一個月,我一直在做單據導入功能,其中就涉及到Excel操作,接觸Excel后發現他的api說明並不多,好在網上有很多朋友貼出了一些代碼,我在不斷的挫折中吸取了很多教訓,現共享出來,給大家參考。

 

1. 最好在客戶端使用,不要在B/S服務端使用,因為會受到IIS權限和占用內存影響,多人並發操作必然完蛋   

 

2. 需要引入兩個DLL,Microsoft.Office.Interop.Excel.dll和office.dll,在加上項目的時候,會報錯“類型“Microsoft.Office.Interop.Excel.ApplicationClass” 未定義構造函數無法嵌入互操作類型“Microsoft.Office.Interop.Excel.ApplicationClass”。請改用適用的接口。”,這時只需要將將引用的DLL:Microsoft.Office.Interop.Excel;的嵌入互操作類型改為false,就可以了

 

3. 注意Excel中sheetindex, rowindex,columnindex都是從1開始的

 

4. 理清Excel里面的對象(Application、Workbook、Worksheet、Range),其中Range包含行和列還有單元格,很多方法都是弱類型object,需要拆箱和裝箱操作,循環讀取效率並不高,所以我在讀取大批量數據Excel時,采用的方式是將Excel調用另存為csv文件,再通過文本操作字符串的方式解析csv文件,讀取每一行,實踐證明,這樣的效率比較高。解析csv文件在附件可以供大家下載 

 

5. 客戶端必須正確安裝office2003或office2007,如果是安裝的wps系列的,需卸載后再重新安裝office

 

這里我貼出我封裝Excel的操作類,希望能對大家有所幫助,歡迎大家指正:

 

 /// <summary>
    /// author by :ljun /// Excel工具類,目前僅支持一個工作薄的操作 /// </summary>
    public class ExcelHelper : IDisposable { #region 構造函數

        /// <summary>
        /// 構造函數,將一個已有Excel工作簿作為模板,並指定輸出路徑 /// </summary>
        /// <param name="templetFilePath">Excel模板文件路徑</param>
        /// <param name="outputFilePath">輸出Excel文件路徑</param>
        public ExcelHelper(string templetFilePath, string outputFilePath) { if (templetFilePath == null) throw new Exception("Excel模板文件路徑不能為空!"); if (outputFilePath == null) throw new Exception("輸出Excel文件路徑不能為空!"); if (!File.Exists(templetFilePath)) throw new Exception("指定路徑的Excel模板文件不存在!"); this.templetFile = templetFilePath; this.outputFile = outputFilePath; excelApp = new Excel.ApplicationClass(); excelApp.Visible = false; excelApp.DisplayAlerts = false;  //是否需要顯示提示
            excelApp.AlertBeforeOverwriting = false;  //是否彈出提示覆蓋 //打開模板文件,得到WorkBook對象
            workBook = excelApp.Workbooks.Open(templetFile, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, Type.Missing, Type.Missing); //得到WorkSheet對象
            workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1); } /// <summary>
        /// 構造函數,新建一個工作簿 /// </summary>
        public ExcelHelper() { excelApp = new Excel.ApplicationClass(); excelApp.Visible = false; //設置禁止彈出保存和覆蓋的詢問提示框
            excelApp.DisplayAlerts = false; excelApp.AlertBeforeOverwriting = false; //新建一個WorkBook
            workBook = excelApp.Workbooks.Add(Type.Missing); //得到WorkSheet對象
            workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1); } #endregion

        #region 私有變量

        private string templetFile = null; private string outputFile = null; private object missing = System.Reflection.Missing.Value; private Excel.Application excelApp; private Excel.Workbook workBook; private Excel.Worksheet workSheet; private Excel.Range range; private Excel.Range range1; private Excel.Range range2; #endregion

        #region 公共屬性

        /// <summary>
        /// WorkSheet數量 /// </summary>
        public int WorkSheetCount { get { return workBook.Sheets.Count; } } /// <summary>
        /// Excel模板文件路徑 /// </summary>
        public string TempletFilePath { set { this.templetFile = value; } } /// <summary>
        /// 輸出Excel文件路徑 /// </summary>
        public string OutputFilePath { set { this.outputFile = value; } } #endregion

        #region 批量寫入Excel內容

        /// <summary>
        /// 將二維數組數據寫入Excel文件 /// </summary>
        /// <param name="arr">二維數組</param>
        /// <param name="top">行索引</param>
        /// <param name="left">列索引</param>
        public void ArrayToExcel(object[,] arr, int top, int left) { int rowCount = arr.GetLength(0); //二維數組行數(一維長度)
            int colCount = arr.GetLength(1); //二維數據列數(二維長度)
 range = (Excel.Range)workSheet.Cells[top, left]; range = range.get_Resize(rowCount, colCount); range.FormulaArray = arr; } #endregion

        #region 行操作

        /// <summary>
        /// 插行(在指定行上面插入指定數量行) /// </summary>
        /// <param name="rowIndex"></param>
        /// <param name="count"></param>
        public void InsertRows(int rowIndex, int count) { try { range = (Excel.Range)workSheet.Rows[rowIndex, this.missing]; for (int i = 0; i < count; i++) { range.Insert(Excel.XlDirection.xlDown, missing); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary>
        /// 復制行(在指定行下面復制指定數量行) /// </summary>
        /// <param name="rowIndex"></param>
        /// <param name="count"></param>
        public void CopyRows(int rowIndex, int count) { try { range1 = (Excel.Range)workSheet.Rows[rowIndex, this.missing]; for (int i = 1; i <= count; i++) { range2 = (Excel.Range)workSheet.Rows[rowIndex + i, this.missing]; range1.Copy(range2); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary>
        /// 刪除行 /// </summary>
        /// <param name="sheetIndex"></param>
        /// <param name="rowIndex"></param>
        /// <param name="count"></param>
        public void DeleteRows(int rowIndex, int count) { try { for (int i = 0; i < count; i++) { range = (Excel.Range)workSheet.Rows[rowIndex, this.missing]; range.Delete(Excel.XlDirection.xlDown); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } #endregion

        #region 列操作

        /// <summary>
        /// 插列(在指定列右邊插入指定數量列) /// </summary>
        /// <param name="columnIndex"></param>
        /// <param name="count"></param>
        public void InsertColumns(int columnIndex, int count) { try { range = (Excel.Range)(workSheet.Columns[columnIndex, this.missing]);  //注意:這里和VS的智能提示不一樣,第一個參數是columnindex

                for (int i = 0; i < count; i++) { range.Insert(Excel.XlDirection.xlDown, missing); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } /// <summary>
        /// 刪除列 /// </summary> 
        /// <param name="columnIndex"></param>
        /// <param name="count"></param>
        public void DeleteColumns(int columnIndex, int count) { try { for (int i = columnIndex + count-1; i >=  columnIndex; i--) { ((Excel.Range)workSheet.Cells[1, i]).EntireColumn.Delete(0); } } catch (Exception e) { this.KillExcelProcess(false); throw e; } } #endregion

        #region 單元格操作

        /// <summary>
        /// 合並單元格,並賦值,對指定WorkSheet操作 /// </summary>
        /// <param name="sheetIndex">WorkSheet索引</param>
        /// <param name="beginRowIndex">開始行索引</param>
        /// <param name="beginColumnIndex">開始列索引</param>
        /// <param name="endRowIndex">結束行索引</param>
        /// <param name="endColumnIndex">結束列索引</param>
        /// <param name="text">合並后Range的值</param>
        public void MergeCells(int beginRowIndex, int beginColumnIndex, int endRowIndex, int endColumnIndex, string text) { range = workSheet.get_Range(workSheet.Cells[beginRowIndex, beginColumnIndex], workSheet.Cells[endRowIndex, endColumnIndex]); range.ClearContents(); //先把Range內容清除,合並才不會出錯
            range.MergeCells = true; range.Value2 = text; range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; } /// <summary>
        /// 向單元格寫入數據,對當前WorkSheet操作 /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <param name="columnIndex">列索引</param>
        /// <param name="text">要寫入的文本值</param>
        public void SetCells(int rowIndex, int columnIndex, string text) { try { workSheet.Cells[rowIndex, columnIndex] = text; } catch { this.KillExcelProcess(false); throw new Exception("向單元格[" + rowIndex + "," + columnIndex + "]寫數據出錯!"); } } /// <summary>
        /// 向單元格寫入數據,對當前WorkSheet操作 /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <param name="columnIndex">列索引</param>
        /// <param name="text">要寫入的文本值</param>
        public void SetCells(int rowIndex, int columnIndex, string text, string comment) { try { workSheet.Cells[rowIndex, columnIndex] = text; SetCellComment(rowIndex, columnIndex, comment); } catch { this.KillExcelProcess(false); throw new Exception("向單元格[" + rowIndex + "," + columnIndex + "]寫數據出錯!"); } } /// <summary>
        /// 向單元格寫入數據,對當前WorkSheet操作 /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <param name="columnIndex">列索引</param>
        /// <param name="text">要寫入的文本值</param>
        public void SetCellComment(int rowIndex, int columnIndex, string comment) { try { Excel.Range range = workSheet.Cells[rowIndex, columnIndex] as Excel.Range; range.AddComment(comment); } catch { this.KillExcelProcess(false); throw new Exception("向單元格[" + rowIndex + "," + columnIndex + "]寫數據出錯!"); } } /// <summary>
        /// 單元格背景色及填充方式 /// </summary>
        /// <param name="startRow">起始行</param>
        /// <param name="startColumn">起始列</param>
        /// <param name="endRow">結束行</param>
        /// <param name="endColumn">結束列</param>
        /// <param name="color">顏色索引</param>
        public void SetCellsBackColor(int startRow, int startColumn, int endRow, int endColumn, ColorIndex color) { Excel.Range range = excelApp.get_Range(excelApp.Cells[startRow, startColumn], excelApp.Cells[endRow, endColumn]); range.Interior.ColorIndex = color; } #endregion

        #region 保存文件

        /// <summary>
        /// 另存文件 /// </summary>
        public void SaveAsFile() { if (this.outputFile == null) throw new Exception("沒有指定輸出文件路徑!"); try { workBook.SaveAs(outputFile, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); } catch (Exception e) { throw e; } finally { this.Quit(); } } /// <summary>
        /// 將Excel文件另存為指定格式 /// </summary>
        /// <param name="format">HTML,CSV,TEXT,EXCEL,XML</param>
        public void SaveAsFile(SaveAsFileFormat format) { if (this.outputFile == null) throw new Exception("沒有指定輸出文件路徑!"); try { switch (format) { case SaveAsFileFormat.HTML: { workBook.SaveAs(outputFile, Excel.XlFileFormat.xlHtml, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } case SaveAsFileFormat.CSV: { workBook.SaveAs(outputFile, Excel.XlFileFormat.xlCSV, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } case SaveAsFileFormat.TEXT: { workBook.SaveAs(outputFile, Excel.XlFileFormat.xlUnicodeText, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } case SaveAsFileFormat.XML: { workBook.SaveAs(outputFile, Excel.XlFileFormat.xlXMLSpreadsheet, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); break; } default: { workBook.SaveAs(outputFile, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing); break; } } } catch (Exception e) { throw e; } finally { this.Quit(); } } #endregion

        #region 殺進程釋放資源

        /// <summary>
        /// 結束Excel進程 /// </summary>
        public void KillExcelProcess(bool bAll) { if (bAll) { KillAllExcelProcess(); } else { KillSpecialExcel(); } } [DllImport("user32.dll", SetLastError = true)] static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId); /// <summary>
        /// 殺特殊進程的Excel /// </summary>
        public void KillSpecialExcel() { try { if (excelApp != null) { int lpdwProcessId; GetWindowThreadProcessId((IntPtr)excelApp.Hwnd, out lpdwProcessId); if (lpdwProcessId > 0)    //c-s方式
 { System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill(); } else { Quit(); } } } catch { } } /// <summary>
        /// 釋放資源 /// </summary>
        public void Quit() { if (workBook != null) workBook.Close(null, null, null); if (excelApp != null) { excelApp.Workbooks.Close(); excelApp.Quit(); } if (range != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(range); range = null; } if (range1 != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(range1); range1 = null; } if (range2 != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(range2); range2 = null; } if (workSheet != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet); workSheet = null; } if (workBook != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook); workBook = null; } if (excelApp != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); excelApp = null; } GC.Collect(); } /// <summary>
        /// 接口方法 釋放資源 /// </summary>
        public void Dispose() { Quit(); } #endregion

        #region 靜態方法

        /// <summary>
        /// 殺Excel進程 /// </summary>
        public static void KillAllExcelProcess() { Process[] myProcesses; myProcesses = Process.GetProcessesByName("Excel"); //得不到Excel進程ID,暫時只能判斷進程啟動時間
            foreach (Process myProcess in myProcesses) { myProcess.Kill(); } } /// <summary>
        /// 打開相應的excel /// </summary>
        /// <param name="filepath"></param>
        public static void OpenExcel(string filepath) { Excel.Application xlsApp = new Excel.Application(); xlsApp.Workbooks.Open(filepath); xlsApp.Visible = true; } #endregion } /// <summary>
    /// 常用顏色定義,對就Excel中顏色名 /// </summary>
    public enum ColorIndex { 無色 = -4142, 自動 = -4105, 黑色 = 1, 褐色 = 53, 橄欖 = 52, 深綠 = 51, 深青 = 49, 深藍 = 11, 靛藍 = 55, 灰色80 = 56, 深紅 = 9, 橙色 = 46, 深黃 = 12, 綠色 = 10, 青色 = 14, 藍色 = 5, 藍灰 = 47, 灰色50 = 16, 紅色 = 3, 淺橙色 = 45, 酸橙色 = 43, 海綠 = 50, 水綠色 = 42, 淺藍 = 41, 紫羅蘭 = 13, 灰色40 = 48, 粉紅 = 7, 金色 = 44, 黃色 = 6, 鮮綠 = 4, 青綠 = 8, 天藍 = 33, 梅紅 = 54, 灰色25 = 15, 玫瑰紅 = 38, 茶色 = 40, 淺黃 = 36, 淺綠 = 35, 淺青綠 = 34, 淡藍 = 37, 淡紫 = 39, 白色 = 2 } /// <summary>
    /// HTML,CSV,TEXT,EXCEL,XML /// </summary>
    public enum SaveAsFileFormat { HTML, CSV, TEXT, EXCEL, XML }

 

同時分享調用方,我用的WinForm給大家寫得示例,以下是窗口截圖:

 

 

有興趣的朋友可以 下載附件 

 


免責聲明!

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



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