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

时间:2021-02-25 08:19:23

I can't seem to find the proper way to open and close an excel file.

我似乎找不到正确的方法来打开和关闭excel文件。

Here is what I have to open my file, which I find overly complicated:

下面是我要打开的文件,我觉得太复杂了:

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

I have no idea how to properly close it. I need to save it with the same path and make sure excel is not still running in the background after it is closed.

我不知道如何正确地关闭它。我需要用同样的方法来保存它,确保excel在关闭后不会在后台运行。

Can someone make it easy for me? Thanks

有人能让我轻松一下吗?谢谢

2 个解决方案

#1


2  

Semi pseudo-code:

半伪代码:

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();

#2


4  

Release the COM objects when completed...

完成后释放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);

#1


2  

Semi pseudo-code:

半伪代码:

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();

#2


4  

Release the COM objects when completed...

完成后释放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);