使用C#into Array读取Excel第一列

时间:2012-12-14 21:14:28

标签: c# excel excel-interop

我正在尝试将第一列的值读入数组。最好的方法是什么?下面是我到目前为止的代码。基本上我正在尝试获取该列的数据范围,以便将单元格值拉入系统数组。

Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();

if (xlsApp == null)
{
    Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
    return null;
}

//xlsApp.Visible = true;

Workbook wb = xlsApp.Workbooks.Open(filename, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
Sheets sheets = wb.Worksheets;
Worksheet ws = (Worksheet)sheets.get_Item(1);

//***Breaks Here***
ListColumn column = ws.ListObjects[1].ListColumns[1];
Range range = column.DataBodyRange;
System.Array myvalues = (System.Array)range.Cells.Value;

3 个答案:

答案 0 :(得分:8)

这是我最终使用它来实现它。一旦你知道Columns实际返回一个范围,以这种方式存储它似乎编译并运行正常。这是我的ExcelReader类中的工作方法。我打算在WebDriver上将它用于测试驱动数据。

    public static string[] FirstColumn(string filename)
    {
        Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();

        if (xlsApp == null)
        {
            Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
            return null;
        }

        //Displays Excel so you can see what is happening
        //xlsApp.Visible = true;

        Workbook wb = xlsApp.Workbooks.Open(filename,
            0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
        Sheets sheets = wb.Worksheets;
        Worksheet ws = (Worksheet)sheets.get_Item(1);

        Range firstColumn = ws.UsedRange.Columns[1];
        System.Array myvalues = (System.Array)firstColumn.Cells.Value;
        string[] strArray = myvalues.OfType<object>().Select(o => o.ToString()).ToArray(); 
        return strArray;
    }

答案 1 :(得分:2)

首先,我会弄清楚实际使用了多少行:

Excel.Range allCellsInColumn = xlWorksheet.Range["A:A"];
Excel.Range usedCells = allCellsInColumn.Find("*", Missing.Value, Missing.Value, Missing.Value,
    Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlPrevious, false, Missing.Value, Missing.Value);

完成后,您可以检索值:

System.Array values = usedCells.Values;

获得数组中的值后,您可以跳过其中没有任何内容的元素。我不认为有一种方法可以只检索带有内容的单元格,而无需一次一个地循环遍历它们,这在Interop中非常耗时。

答案 2 :(得分:0)

您的数据是否在列表中?您的代码似乎正在寻找可能不存在的Excel列表。如果不是,您可以将整个第一列(A:A)放入一个范围并获取它的值:

Range firstCol = ws.Range("A:A");
System.Array values = range.Value as System.Array;