如何从Range类型的“名称字符串”获取列

时间:2014-09-14 08:45:19

标签: c# string excel

例如我在excel文件中:

colname1 colname2 colname3
1 2 3
4 2 4
5 6 4
6 1 2

这是我的代码的一部分:

 public IList<Range> GetColVal(string _path)
    {


        IList<Range> rowList= new List<Range>();
        System.Data.DataTable tableExcel = new System.Data.DataTable();

        FileInfo fileInfo = new FileInfo(_path);     
        app = new Microsoft.Office.Interop.Excel.Application();
        wb = app.Workbooks.Open(_path, Type.Missing);
        sheet = (Worksheet)wb.Sheets[1];
        Range excelRange = sheet.UsedRange;
        int colCount = excelRange.Columns.Count;
        int rowCount = excelRange.Rows.Count;
        Range tmpVar;
        for (int i = 1; i <= rowCount; i++)
        {
            tmpVar = sheet.Rows[i];
            rowList.Add(tmpVar);

        }
        return rowList;
    }

我希望每行按列名称获取字段,然后按foreach

进行迭代

例如

foreach(var a in ListRows)
{
a["colname1"] ...
}

如何在每行中包含col名称?

1 个答案:

答案 0 :(得分:0)

我做了这个

static DataTable ExcelToDataTable(string FilePath, string Extension, string isHDR)
{
    string conStr = "";
    switch (Extension)
    {
        case ".xls": //Excel 97-03
            conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
            break;
        case ".xlsx": //Excel 07
            conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}";
            break;
    }

    conStr = String.Format(conStr, FilePath, isHDR);
    OleDbConnection connExcel = new OleDbConnection(conStr);
    OleDbCommand cmdExcel = new OleDbCommand();
    OleDbDataAdapter oda = new OleDbDataAdapter();
    DataTable dt = new DataTable();
    cmdExcel.Connection = connExcel;

    //Get the name of First Sheet
    connExcel.Open();
    DataTable dtExcelSchema;
    dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
    connExcel.Close();

    //Read Data from First Sheet
    connExcel.Open();
    cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
    oda.SelectCommand = cmdExcel;
    oda.Fill(dt);
    connExcel.Close();
    return dt;
}

使用它就像这样

DataTable dt = ExcelToDataTable(@"C:\Users\Nikhil\Desktop\1.xls", ".xls", "true");

然后,您可以使用列名称循环数据表。