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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1526685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:26:27  来源:igfitidea点击:

C#: How can I open and close an Excel workbook?

c#exceloffice-interopaspose

提问by Jim G.

Does anyone know how to simply open and close an Excel workbook?

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

I don't need to read any data from the file, I just need to open and close it. (*)

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

I'm guessing that I'll need to reference the Microsoft.Office.Interop.Excel assembly.

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



*Reason: I've already configured pivot table information with a 3rd party library (Aspose). Now I need to read the generated pivot table.

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

Unfortunately, the Aspose library can't generate the pivot table at runtime. It needs someone to open the file with Excelso that Excel can generate the pivot table values.

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

采纳答案by Gratzy

after referencing Microsoft.Office.Interop.Excel also Make sure to clean up in the finally.

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


        }

回答by Michael Edwards

A quick Google gives me this on code project:

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

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

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

回答by Ed Power

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.

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