c# - c#:访问excel工作表中的单元格抛出NullReferenceException
问题描述
所以我一直在尝试编写一个控制台应用程序(.Net Core),它从 Excel 文件中读取数据,但我有点卡住了。
我一直试图让这个代码示例工作:https ://www.csharp-console-examples.com/general/reading-excel-file-in-c-console-application/
我需要(Range)cell
显式使用,因为当示例代码尝试直接访问单元格时,Visual Studio 会抛出错误。
尝试加载工作表和m_ObjectToDataMap = null
工作表和范围的使用范围时。使用 excelRange.Rows 访问行因 System.NullReferenceException 失败:“对象引用未设置为对象的实例。”
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 结束。
任何帮助,将不胜感激。
解决方案
我认为您使用的代码参考是 .NET Framework 中的控制台应用程序。我使用了您引用的此处的代码并将其放入 .NET Framework 控制台应用程序中,它运行良好。我将相同的代码放在 .NET Core 控制台应用程序中,但它不起作用。因此,您可能需要更改为 .NET Framework,或者您可以使用另一个 Excel 库。我使用 NPOI,您可以在此处遵循示例或进行更多谷歌搜索以查找其他示例。可能还有更多像EPPlus这样的库可以在 .NET Core 中用于解析 excel,但我没有使用或研究过任何其他库。
推荐阅读
- c# - C#如何让不同速度的进程一起工作
- javascript - 回调函数有问题
- python - Python:无名关键字参数列表
- android - Android 单元测试改造失败
- java - 使用 mySQL 从 Spring Boot 开始时,Javers 给出重复的键名“jv_global_id_owner_id_fk_idx”
- kql - 如何在日期之间创建 kql 查询
- three.js - three.js 失真,glb (gltf) 模型上的颜色替换。蓝色变为绿色,黄色变为橙色
- powershell - 在 dc 调用命令 - 获取 gpinheritance - 不起作用
- regex - 如何从以下 reg 表达式响应中排除最后一个字符
- python - 找出列表中直到特定索引的唯一元素的程序