[C#] 讀取寫入EXCEL樣板範例 - 使用Interop.Excel

筆記用C#操作Excel的樣板



/* Excel using */
using Excel =  Microsoft.Office.Interop.Excel;

//在Class內定義 initialExcel()
        Excel.Application initailExcel()
        {
            bool flag = false;
            Excel.Application _Excel = null;

            /* 檢查PC有無Excel在執行 */
            foreach (var item in Process.GetProcesses())
            {
                if (item.ProcessName == "EXCEL")
                {
                    flag = true;
                    break;
                }
            }

            if (!flag)
            {
                _Excel = new Excel.Application();
            }
            else
            {
                object obj = Marshal.GetActiveObject("Excel.Application");//引用已在執行的Excel
                _Excel = obj as Excel.Application;
            }

            _Excel.Visible = false; //設定隱藏背景excel視窗
            _Excel.UserControl = false;
            _Excel.DisplayAlerts = false;
            return _Excel;
        }


void Main()
{
    Excel.Application oXL = initailExcel();
    Excel.Workbook wkb; //要開啟的BOM 檔案

    try
    {
        wkb = oXL.Workbooks.Open(ofd.FileName, ReadOnly: true);

        // Do something

    }
    catch (Exception ex)
    {
        MessageBox.Show("Something wrong with EXCEL operation, please close all EXCEL process in memory and try again. \n " + ex.Message);
        wkb.Close(false);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(wkb);
        wkb = null;
        oXL.Workbooks.Close();
        oXL.Quit();
        System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL);
        oXL = null;
        return;
    }



相關系列文章:

留言

這個網誌中的熱門文章

[TCL] 基本語法與指令 - 2. TCL 語法

[TCL] 基本語法與指令 - 1. TCL 簡介

[TCL] 基本語法與指令 - 3. 資料型態