close
要使用之前要先安裝 Excel 跟 .Net Framework 2.0
而如果安裝順序為 1.Excel 2..Net Framework 2.0
則程式可能會出現錯誤
解決方式為
下載 Office .Net 支援套件
連結

在專案中
請先加入參考  "COM"->"Microsoft Excel Object Library"

之後在程式中加入
using Microsoft.Office.Interop.Excel;

寫入檔案範例:
            ApplicationClass app = new ApplicationClass();
            Workbook book = null;
            Worksheet sheet = null;
            Range range = null;

            try
            {
                app.Visible = false;
                app.ScreenUpdating = false;
                app.DisplayAlerts = false;

                string execPath = Path.GetDirectoryName("D:\\test");

                book = app.Workbooks.Add(true);
                sheet = (Worksheet)book.Worksheets[1];

                sheet.get_Range("A1", "A1").Value2 = "丁丁";
                sheet.get_Range("A2", "A2").Value2 = "丁丁";

                book.SaveAs(execPath + @"test\test.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                range = null;
                if (book != null)
                    book.Close(false, "test.xls", null);
                if (app != null)
                    app.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet );
                System.Runtime.InteropServices.Marshal.ReleaseComObject(book );
                System.Runtime.InteropServices.Marshal.ReleaseComObject(app );
                sheet = null;
                book = null;
                app = null;
                GC.Collect();
            }

參考網站
參考網站2
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 JohnDX 的頭像
    JohnDX

    我要回家想一想~

    JohnDX 發表在 痞客邦 留言(0) 人氣()