[C#] 對Excel進行讀寫

首先,要先加入 Microsoft Excel 16.0 Object Library 的參考,只要電腦有安裝Excel應該都可以在COM中找到
然後參考
using Excel = Microsoft.Office.Interop.Excel;

呼叫Excel有三個步驟
分別是Application、Workbook、跟Worksheet

Application可以透過 Visible與UserControl的屬性控制是否要在前景顯示

剩下的就參考一下以下程式碼吧,這是在revit api中呼叫excel寫入資料的練習

值得注意的是為避免程式執行完之後留下多餘的Excel在後端,需要用try catch finally的方式確保無論程式是否執行成功,都有釋放Excel所占資源

                //Output 鋼筋表
                //存檔路徑
                string savefilename = "";
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Excel活頁簿(*.xlsx)|*.xlsx|所有檔案(*.*)|*.*";
                saveFileDialog1.Title = "Export Rebar Table";
                if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    savefilename = saveFileDialog1.FileName;
                else return Result.Cancelled;

                //開excel
                Excel.Application eapp = new Excel.Application();
                Excel.Workbook ebook = null;
                Excel.Worksheet esheet = null;
                Excel.Range oRng;
                int er = 0;
                try
                {
                    eapp.Visible = false;
                    eapp.UserControl = false;
                    ebook = eapp.Workbooks.Add(Missing.Value);
                    esheet = (Excel.Worksheet)ebook.ActiveSheet;
                    oRng = esheet.get_Range("A1", "H250");
                    int row = 2;
                    esheet.Cells[1, 1] = "Size";
                    esheet.Cells[1, 2] = "Color";
                    foreach (var e in rebarmap)
                    {
                        esheet.Cells[row, 1] = e.Key;
                        esheet.Cells[row, 2] = e.Value;
                        row++;
                    }
                    oRng.EntireColumn.AutoFit();
                    ebook.SaveAs(savefilename);
                }
                catch (Exception ex)
                {
                    er++;
                    MessageBox.Show(ex.Message, "Exception");
                }
                finally
                {
                    excelquit(eapp, ebook, esheet);//確定確實關掉Excel
                }
                if (er > 0) return Result.Failed;
                else return Result.Succeeded;
            }
            else if (dialogResult == DialogResult.No)
            {
                return Result.Succeeded;
            }
            else return Result.Cancelled;

        }
        //確實關掉Excel
        static public void excelquit(Excel.Application eapp, Excel.Workbook ebook, Excel.Worksheet esheet)
        {
            if (esheet != null)
            {
                Marshal.FinalReleaseComObject(esheet);
            }
            if (ebook != null)
            {
                ebook.Close(false); //忽略尚未存檔內容,避免跳出提示卡住
                Marshal.FinalReleaseComObject(ebook);
            }
            if (eapp != null)
            {
                eapp.Workbooks.Close();
                eapp.Quit();
                Marshal.FinalReleaseComObject(eapp);
            }
        }

留言

這個網誌中的熱門文章

[C#] WinForm動態側邊欄

在Windows Form 上瀏覽 PDF

[C#] Windows Form 自訂控制項