C# - 以编程方式打开和关闭excel文件的正确方法

Sim*_*mon 4 c# excel

我似乎无法找到打开和关闭excel文件的正确方法.

这是我必须打开我的文件,我发现它过于复杂:

        Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

        Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
            0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
            true, false, 0, true, false, false);
        Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;

        Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)excelApp.Worksheets[2];
        sheet.Select(Type.Missing);
Run Code Online (Sandbox Code Playgroud)

我不知道如何正确关闭它.我需要使用相同的路径保存它,并确保excel在关闭后仍然不在后台运行.

有人可以让我轻松吗?谢谢

小智 9

完成后释放COM对象...

using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

# declare the application object
var xl = new Excel.Application();

# open a file
var wb = xl.Workbooks.Open("some_file.xlsx");


# close the file
wb.Close();

# close the application and release resources
xl.Quit();

#release the COM objects created as a final step:

Marshal.ReleaseComObject(wb);
Marshal.ReleaseComObject(xl);
Run Code Online (Sandbox Code Playgroud)


Dav*_*vid 5

半伪代码:

using Excel = Microsoft.Office.Interop.Excel;

# declare the application object
Excel.Application xl = new Excel.Application();

# open a file
Excel.Workbook wb = xl.Workbooks.Open("some_file.xlsx");

# do stuff ....

# close the file
wb.Close();

# close the application and release resources
xl.Quit();
Run Code Online (Sandbox Code Playgroud)