通过C#中的OleDbDataAdapter导入Excel通过更改列名称

你好,我尝试导入一个Excel文档到我的DataGridView在C#中。 到目前为止,它的工作,但有一个数据列,我需要“sorting”。

如果这很简单,我会在OleDbDataAdapter查询中执行“WHERE test> 0”。

但是..列的名称正在改变与每个文件,我需要经常使用它。 到目前为止,我得到这个:

private void button1_Click(object sender, EventArgs e) { String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\Users\\Test\\Desktop\\Test.xls;" + "Extended Properties=Excel 8.0;"; DataSet ds = new DataSet(); OleDbDataAdapter da = new OleDbDataAdapter ("SELECT * FROM [Test$]", strConn); da.Fill(ds); dataGridView1.DataSource = ds.Tables[0].DefaultView; } 

在select我需要把一个女巫的状态,列的前3个字母是相同的,但后面的数字不是。 喜欢:

QTA 12345,QTA 13213,QTA 92818。

就像是:

  OleDbDataAdapter da = new OleDbDataAdapter ("SELECT * FROM [Test$] WHERE [testColumn] > 0", strConn); 

但随后与前3个字母和最后的数字是随机的。

有人能帮助我吗?

我试过一些代码,它对我来说工作正常。 试试:

 OleDbConnection oleDbConnection = new OleDbConnection( "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=D:\\Users\\name\\Desktop\\test.xls;" + "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"); oleDbConnection.Open(); //Get columns DataTable dtColumns = oleDbConnection.GetSchema("Columns", new string[] { null, null, "Tabelle1$", null }); List<string> columns = new List<string>(); foreach (DataRow dr in dtColumns.Rows) columns.Add(dr[3].ToString()); string colName = columns.Find(item => item.Substring(0,3) == "QTA"); DataSet ds = new DataSet(); OleDbDataAdapter da = new OleDbDataAdapter ("SELECT * FROM [Tabelle1$] WHERE [" + colName + "] > 0", oleDbConnection); da.Fill(ds); dataGrid1.ItemsSource = ds.Tables[0].DefaultView; oleDbConnection.Close(); 

请注意根据需要更改连接string。

您可以使用LINQ修剪代码:

 string colName = (from DataRow dr in dtColumns.Rows where dr[3].ToString().Substring(0, 3) == "QTA" select dr[3].ToString()).ElementAt(0);