Excel IndexOutOfRange 与 .NET Core

Excel IndexOutOfRange with .NET Core

基于示例 https://github.com/dotnet/samples/tree/master/core/extensions/ExcelDemo 我可以在 .NET Core 3.1 中获得 Excel 互操作(是的,我意识到 Excel 不完全是跨平台的,但请耐心等待).以下代码在面向 .NET Framework 4.7.2 时运行良好,但在 .NET Core 上,最后一行因 IndexOutOfRangeException "Index was outside the bounds of the array."

而爆炸
Excel.Application excel;
Excel.Workbook workbook;
Excel.Worksheet sheet;
Excel.Range range;

// Start Excel and get Application object.
excel = new Excel.Application();
excel.Visible = true;

// Get a new workbook.
workbook = excel.Workbooks.Add(Missing.Value);
sheet = (Excel.Worksheet)workbook.ActiveSheet;

range = sheet.Range[sheet.Cells[1, 1], sheet.Cells[1, 4]];  //this works fine with .NET Framework but not Core

我尝试广泛移植的遗留代码像这样设置变量范围,否则我会简单地使用像 "A1:D1" 这样的绝对电子表格样式索引,这在 .NET Core 中似乎工作正常。我已经尝试设置 excel.ReferenceStyle = Excel.XlReferenceStyle.xlR1C1 以及 sheet.get_Range(,) 而不是 sheet.Range[] 的排列,但我仍然得到相同的出界问题,尽管它是一个有效范围。有什么想法可以让 Range 调用在 .NET Core 中工作吗?

这里有解决方法,虽然我不知道为什么:

你可以像下面这样调用

Excel.Range oCell1 = sheet.Cells[1, 1];
Excel.Range oCell2 = sheet.Cells[1, 4];
range = sheet.Range[oCell1, oCell2];

范围 = sheet.Range[(Excel.Range)sheet.Cells[1, 1], (Excel.Range)sheet.Cells[1, 4]];