C#: 我该如何打开和关闭Excel工作簿?

9

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

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

我猜我需要引用Microsoft.Office.Interop.Excel程序集。


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

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

3个回答

14

在引用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);


        }

在实现过程中,我遇到了错误:Microsoft.Office.Interop.Excel.ApplicationClass 类型没有定义构造函数,请参考以下链接进行更正。https://dev59.com/02Yr5IYBdhLWcg3wBlvp - Desmond
1
我还会在最后的代码块中添加 _Excel.Quit() 来关闭 Excel 应用程序。 - arthur
1
工作簿的VB项目在关闭工作簿后仍然保持打开状态,有什么解决办法吗? - Sujoy

3

1
考虑使用System.Diagnostics.Process来启动、监控和关闭Excel。这个网站提供了一个很好的介绍:http://www.thescarms.com/dotnet/Process.aspx,包括在不可见窗口下运行和向其发送输入。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接