相关疑难解决方法(0)

如何正确清理Excel互操作对象?

我在C#(ApplicationClass)中使用Excel互操作,并在我的finally子句中放置了以下代码:

while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { }
excelSheet = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Run Code Online (Sandbox Code Playgroud)

虽然这种工作,Excel.exe即使我关闭Excel后,该过程仍然在后台.只有在我的应用程序手动关闭后才会发布.

我做错了什么,或者是否有其他方法可以确保互操作对象得到妥善处理?

c# excel interop com-interop

733
推荐指数
20
解决办法
30万
查看次数

如何在C#中访问已打开的Excel文件?

我在Windows资源管理器中双击打开了excel工作簿,但无法在代码中访问它

Excel.Application xlApp = (Application)Marshal.GetActiveObject("Excel.Application");
Excel.Workbooks xlBooks = xlApp.Workbooks;
Run Code Online (Sandbox Code Playgroud)

xlBooks.Count等于0,为什么不引用我打开的工作簿?

编辑

以下是各种场景和发生的情况:

场景1:如果文件尚未打开

  • 代码打开工作簿,我很高兴.

场景2:如果文件最初是从代码打开的,我关闭并重新打开应用程序

  • 代码引用文件就好了xlBooks.Count等于1,我很高兴.

场景3:如果文件最初不是从代码打开,而是通过在资源管理器中双击它

  • 代码打开文件的另一个实例xlBooks.Count等于0,我很愤怒!

这是现在的整个代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

public class ExcelService : IExcelService
{
    const string _filePath = @"C:\Somewhere";
    const string _fileName = @"TestFile.xlsb";
    string _fileNameAndPath = Path.Combine(_filePath, _fileName);

    Application xlApp;
    Workbooks xlBooks;
    Workbook xlBook;
    Worksheet xlSheet;

    public ExcelService()
    {
        try
        {
            xlApp = (Application)Marshal.GetActiveObject("Excel.Application");
            xlBooks = xlApp.Workbooks;

            var numBooks = …
Run Code Online (Sandbox Code Playgroud)

c# excel ms-office office-interop excel-interop

6
推荐指数
2
解决办法
1万
查看次数