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

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

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

谁能帮我解决这个问题? 谢谢

最佳答案

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

关于C# - 以编程方式打开和关闭 excel 文件的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30792531/

相关文章:

c# - 你能在asp.net-mvc中强制删除(页面和partialView)OutputCache吗

c# - 如何将页面指向不同的 web.config?

vba - 强制从内存中卸载表单

vba - 无模式 MsgBox、错误捕获、.Find

excel - 如何获得英文字母表中的第n个字母

c# - 在 C# 中是否调用了空构造函数?

c# - 警报在 Chrome 驱动程序中不起作用

c# - "Before the ` catch ` block is executed, the runtime checks for ` finally ` blocks.",什么意思?

vba - Excel 宏非 VBA

excel - Excel 中的索引匹配公式