简体   繁体   English

从Excel文件C#读取列

[英]Read Column from Excel File C#

I have method, which gets the cells from an excel File. 我有方法,它从excel文件中获取单元格。 The problem is that 'if (usedrange.Cells[1, j] != null)' gives an NullReference Exception. 问题是“ if(usedrange.Cells [1,j]!= null)”给出了NullReference异常。 I used that Code at Work on Visual Studio, but now at home its not working. 我在Visual Studio上的工作中使用了该代码,但现在在家里它不起作用。 Can someone tell me why? 有人可以告诉我为什么吗?

   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;
    }

From the code, I could see that the usedRange is created from different Worksheet object ( ws1 ) instead of correct one ( ws ). 从代码中,我可以看到usedRange是从不同的工作表对象( ws1 )创建的,而不是从正确的对象( ws )创建的。 It might be the reason. 这可能是原因。 Change it as below and check. 如下更改并检查。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM