首页 > 解决方案 > 从 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;
    }

标签: c#excel

解决方案


从代码中,我可以看到usedRange是从不同的Worksheet 对象 ( ws1 ) 而不是正确的 ( ws ) 创建的。这可能是原因。如下更改并检查。

Worksheet ws = (Worksheet)wb.Worksheets[1];
Range usedrange = ws.UsedRange;

推荐阅读