如何使用互操作在C#视图中读取受保护的Excel文件?

如何使用互操作在C#视图中读取受保护的Excel文件?,c#,excel,selenium,C#,Excel,Selenium,我正在使用使用Excel=Microsoft.Office.Interop.Excel打开excel文件并通读。但是,我无法从中获取单元格D4的值。rangeObject正在变为null有什么想法吗 以下是我正在使用的excel表格: 我需要得到单元格D4的值,也就是9 public static string GetAmountFromReport() { var fileName = string.Empty; var downloadedFiles

我正在使用
使用Excel=Microsoft.Office.Interop.Excel
打开excel文件并通读。但是,我无法从中获取单元格D4的值。
rangeObject
正在变为
null
有什么想法吗

以下是我正在使用的excel表格:

我需要得到单元格D4的值,也就是9

public static string GetAmountFromReport()
    {
        var fileName = string.Empty;
        var downloadedFilesPath = Path.Combine(Directory.GetCurrentDirectory(),
            @"TestAutomationFramework\Utilities\DownloadedFiles");
        var directoryInfo = new DirectoryInfo(downloadedFilesPath);
        var files = directoryInfo.GetFiles("report_export_*.xlsx");
        Thread.Sleep(3000);
        fileName = files[0].Name;
        var fullPathToFile = downloadedFilesPath + "\\" + fileName;

        var xls = new Excel.Application();
        var workBooks = xls.Workbooks;
        var workBook = workBooks.Open(fullPathToFile, ReadOnly: false, IgnoreReadOnlyRecommended: true);
        var sheets = workBook.Worksheets;
        var workSheet1 = (Excel.Worksheet)sheets[1];
        var rangeObject = workSheet1.Cells[4, "D"] as Excel.Range;
        var amountFromCell = rangeObject.Value.ToString();

        // removing from Memory
        Marshal.ReleaseComObject(sheets);
        workBook.Close();
        Marshal.ReleaseComObject(workBook);
        Marshal.ReleaseComObject(workBooks);

        xls.Application.Quit(); // THIS IS WHAT IS CAUSES EXCEL TO CLOSE
        xls.Quit();
        Marshal.ReleaseComObject(xls);

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

        foreach (var file in directoryInfo.GetFiles())
        {
            file.Delete();
        }
        return amountFromCell;
    }

我建议跳过互操作并使用nuget包:。它不需要在运行的机器上使用excel,也可以在核心应用程序的Linux版本中使用

该库不支持受密码保护的excel文件