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

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;

最佳答案

这就是我最终用来使其正常工作的东西。一旦您知道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;
    }

关于c# - 使用C#将Excel第一栏读入数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13886330/

10-13 07:06
查看更多