从 Excel 读取:该进程无法访问该文件,因为它正被另一个进程使用

Reading from Excel: The process cannot access the file because it's being used by another process

我正在尝试从 .xslx 文件的范围内读取多个单元格。 我得到一个进程无法访问该文件的错误,因为它正被另一个进程使用。

首先我遇到了本主题中描述的问题:()。我通过 运行ning 修复 MSOffice Professional Plus 解决了这个问题。完成后,代码块开始出现我提到的错误。为了测试它们的行为,我创建了一个新项目,它最终得到了同样的错误。

我正在使用以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;

namespace EA_Excel_ReadRange
{
class Program
{
    static void Main(string[] args)
    {

                    Excel.Application xlApp = new Excel.Application();
        Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"PathToXslx");
        Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
        Excel.Range xlRange = xlWorksheet.UsedRange;

        int rowCount = xlRange.Rows.Count;
        int colCount = xlRange.Columns.Count;

        for (int i = 1; i <= rowCount; i++)
        {
            for (int j = 1; j <= colCount; j++)
            {
                if (j == 1)
                    Console.Write("\r\n");

                if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
                    Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
            }
        }

        GC.Collect();
        GC.WaitForPendingFinalizers();

        Marshal.ReleaseComObject(xlRange);
        Marshal.ReleaseComObject(xlWorksheet);

        xlWorkbook.Close();
        Marshal.ReleaseComObject(xlWorkbook);

        xlApp.Quit();
        Marshal.ReleaseComObject(xlApp);

    }
}

}

我可以 运行 一次代码,如果没有找到我会收到警告,我应该检查它是否在那里,等等。在那之后我在 VS 2019 中遇到以下错误社区。我也检查了任务管理器,但没有错误消息中描述的过程。

Could not copy "obj\Debug\EA_Excel_ReadRange.exe" to "bin\Debug\EA_Excel_ReadRange.exe". Exceeded retry count of 10. Failed. The file is locked by: "EA_Excel_ReadRange.exe (21944)" EA_Excel_ReadRange

&

Unable to copy file "obj\Debug\EA_Excel_ReadRange.exe" to "bin\Debug\EA_Excel_ReadRange.exe". The process cannot access the file 'bin\Debug\EA_Excel_ReadRange.exe' because it is being used by another process. EA_Excel_ReadRange

请解释为什么 会出现这些错误,如何 我可以修复它们,这样代码就会运行。我最近才开始用 C# 编程,所以我可能在我的代码中遗漏了一些导致这些错误的东西。

如果我需要澄清一些事情,请告诉我。

编辑 我正在使用的文件是从 Sharepoint on Premises

上的 Excel 在线公司 sheet 下载的

正如 Hans Passant 和 Liam 在他们的评论中所解释的那样,我的文件被另一个进程使用了​​。虽然该进程未在任务管理器中列出,但它仍然是 运行。 我在网上搜索了另一种方法来确定进程以及如何终止它,我发现了两个 cmdlet: 首先,我以管理员权限启动 PowerShell,并使用 cmdlet "Get-Process [-name]" 检查是否有名为“EA_Excel_ReadRange.

的进程
Get-Process EA_Excel_ReadRange

其次,我在cmdlet"Stop-Process [-ID]"中使用了这个cmdlet返回的ID,杀死了导致文件无法访问的进程

Stop-Process -id 21944