c# - 从 Excel 文件 C# 中读取列
问题描述
我有方法,它从 excel 文件中获取单元格。问题是 'if (usedrange.Cells[1, j] != null)' 给出了 NullReference 异常。我在 Visual Studio 上使用了该代码,但现在在家里它不起作用。有人能告诉我为什么吗?
public List<string> GetBrandListFromExcel(string path, int sheet)
{
var i = 1;
var j = 1;
List<string> zelle = new List<string>(); ;
if (File.Exists(path))
{
Workbook wb = excel.Workbooks.Open(path);
Worksheet ws = (Worksheet)wb.Worksheets[1];
Range usedrange = ws.UsedRange;
for (j = 1; j <= 2250; j++)
{
if (usedrange.Cells[1, j] != null)
{
var cell = usedrange.Cells[j, 1] as Range;
if (cell.Value2 != null)
{
zelle.Add((string)cell.Text);
}
}
else
continue;
}
wb.Close();
}
return brands;
}
解决方案
从代码中,我可以看到usedRange是从不同的Worksheet 对象 ( ws1 ) 而不是正确的 ( ws ) 创建的。这可能是原因。如下更改并检查。
Worksheet ws = (Worksheet)wb.Worksheets[1];
Range usedrange = ws.UsedRange;
推荐阅读
- flutter - 成功数据后如何显示对话框
- dialogflow-es - 如何使用 webhook 在 DialogFlow 中检测环聊卡片点击事件?
- flutter - Flutter Web 的 Twitter 身份验证
- c# - 使用 C# 进行热巧克力验证
- java - 引起:org.postgresql.util.PSQLException:错误:PL/pgSQL 函数上无法识别的配置参数
- android - Android sdk 未安装
- html - 图片元素中的源标记不接受 HTML 中的本地路径
- python - 如何创建具有多个线程的全局列表
- python - pygame.display.toggle_fulscreen() 不工作
- python - Discord py - 从新创建的频道获取频道 ID