按标题名称检索列 [英] Retrieve Column By Header Name

查看:100
本文介绍了按标题名称检索列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用OLEDB从Excel电子表格中读取数据。

I am using OLEDB to read the data from an Excel spreadsheet.

var connectionString =
  string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=Excel 12.0;", fileName);

var adapter = new OleDbDataAdapter("SELECT * FROM [sheet1$]", connectionString);
var ds = new DataSet();

adapter.Fill(ds, "mySheet");
var data = ds.Tables["mySheet"].AsEnumerable();

foreach (var dataRow in data)
  { 
  Console.WriteLine(dataRow[0].ToString());                        
  }

而不是将索引传递给DataRow以获取列的值,有没有通过列标题的名称检索列?

Instead of passing an index to the DataRow to get the value of a column, is there anyway to retrieve the column by the name of the column header?

推荐答案

请尝试以下代码:

        var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=Excel 12.0; HDR=YES", fileName);

        var adapter = new OleDbDataAdapter("SELECT * FROM [sheet1$]", connectionString);
        var ds = new DataSet();

        adapter.Fill(ds, "mySheet");
        var data = ds.Tables["mySheet"].AsEnumerable();

        foreach (DataRow dataRow in data)
        {
            Console.WriteLine(dataRow["MyColumnName"].ToString());    
            Console.WriteLine(dataRow.Field<string>("MyColumnName").ToString());
        }

我以两种方式添加了通过列名访问行中的数据。

I added in 2 ways to access the data in the row via column Name.

希望这样做可以!

这篇关于按标题名称检索列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆