[英]How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries
[英]How to read Excel file that is protected view in C# using Interop?
我正在使用using Excel = Microsoft.Office.Interop.Excel;
打开excel文件并通读它。 但是,我无法从中获取单元格 D4 的值。 rangeObject
正在变为null
任何想法?
这是我正在使用的excel表:
我需要获取 Cell 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;
}
我建议跳过Interop并使用nuget包: ExcelDataReader 。 它在运行的计算机上不需要excel,也可以在Core应用程序的Linux版本中使用。
该库支持受密码保护的excel文件。
您可以使用互操作 API 从 Excel 工作簿中收集的信息不多,但您可以收集的是文件名等。查看下面的示例代码。
var xls = new Excel.Application();
var activeProtectedViewWindow =
xls?.ActiveProtectedViewWindow;
var spath = activeProtectedViewWindow.SourcePath;
var sfname = activeProtectedViewWindow.SourceName;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.