8

有谁知道如何简单地打开和关闭 Excel 工作簿?

我不需要从文件中读取任何数据,我只需要打开和关闭它。(*)

我猜我需要参考 Microsoft.Office.Interop.Excel 程序集。


*原因:我已经使用 3rd 方库 (Aspose) 配置了数据透视表信息。现在我需要阅读生成的数据透视表。

不幸的是,Aspose 库无法在运行时生成数据透视表。它需要有人用 Excel 打开文件,以便 Excel 可以生成数据透视表值。

4

3 回答 3

13

引用 Microsoft.Office.Interop.Excel 后也请务必在 finally 中进行清理。

using Excel = Microsoft.Office.Interop.Excel;

        Excel.ApplicationClass _Excel;
        Excel.Workbook WB;
        Excel.Worksheet WS;

    try
        {

        _Excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
        WB = _Excel.Workbooks.Open("FILENAME",
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing);

            //do something

        }
        catch (Exception ex)
        {
            WB.Close(false, Type.Missing, Type.Missing);

            throw;
        }
        finally
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();

            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(WB);

            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_Excel);


        }
于 2009-10-06T16:41:58.030 回答
3

一个快速的谷歌在代码项目上给了我这个:

http://www.codeproject.com/KB/office/csharp_excel.aspx

于 2009-10-06T16:36:49.180 回答
0

Consider using System.Diagnostics.Process to start, monitor, and close Excel. This site gives a good intro: http://www.thescarms.com/dotnet/Process.aspx, including running with an invisible window and sending input to it.

于 2009-10-06T17:27:30.013 回答