【发布时间】:2019-09-30 11:24:42
【问题描述】:
所以我一直在尝试编写一个控制台应用程序 (.Net Core),它从 Excel 文件中读取数据,但我有点卡住了。
我一直试图让这个代码示例工作:https://www.csharp-console-examples.com/general/reading-excel-file-in-c-console-application/
我需要明确使用(Range)cell,因为当示例代码尝试直接访问单元格时,Visual Studio 会抛出错误。
当尝试为工作表和范围加载工作表和使用的范围 m_ObjectToDataMap = null 时。由于 System.NullReferenceException: 'Object reference not set to an instance of an object.'
static void Main(string[] args)
{
//Create COM Objects.
Application excelApp = new Application();
if (excelApp == null)
{
Console.WriteLine("Excel is not installed!!");
return;
}
Workbook excelBook = excelApp.Workbooks.Open(@"D:\test.xlsx");
_Worksheet excelSheet = (_Worksheet)excelBook.Sheets[1];
Range excelRange = excelSheet.UsedRange;
foreach (Range row in excelRange.Rows) // Here is the NullReference Error
{
// create new line
Console.Write("\r\n");
foreach (Range col in excelRange.Columns)
{
Range cell = (Range)excelRange.Cells[row, col];
// write the console
if (excelRange.Cells[row, col] != null && cell.Value2 != null)
Console.Write(cell.Value2.ToString() + "\t");
}
}
//after reading, relaase the excel project
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
Console.ReadLine();
}
我尝试了很多不同的代码,循环遍历所有工作表或通过其名称调用工作表,但它总是以工作表和范围加载不正确以及 NullReferenceException 结束。
任何帮助将不胜感激。
【问题讨论】:
-
你可能已经合并了单元格...你还需要释放工作表、范围和工作簿
-
出于测试目的,我只是将“测试”写入前 6 个单元格(第 1 行中的 3 个和第 2 行中的 3 个),所以 exel 文件应该没问题
-
我知道 NullReference 是什么,但我找不到如何正确加载工作表(或范围)
-
你为什么要在每个循环中为单个单元格创建一个新的“范围”,只需读取单元格