c# - 使用 C# 将 Excel 第一列读取到数组中

标签 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;

最佳答案

这是我最终用来让它工作的东西。一旦您知道 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/

相关文章:

excel搜索范围特定文本复制包含文本的单元格

c# - 使用 excel introp 或 npoi 从 excel(具有行和单元格位置)读取图像

c# - LINQ 查询帮助

c# - 使用 iTextSharp 将多个页面添加到 pdf 表单

C#:Microsoft.Office.Interop.Excel.Range 的 ID 字段未与 Excel 工作表一起保存

vb.net - 将 Excel 电子表格另存为 PDF

Windows Server 2012 R2 中的 Excel Interop(插入图像)

c# - wpf 形式的所有内容的圆角

c# - 查找一组字符串的第一个公共(public)子串

vba - 检查值是否存在于集合或数组中,如果不存在,则添加