2011-05-04 49 views
15

我新的C#和想读在C#中使用下面的代码的XLSX文件:读取数据从XLSX在C#

string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;DataSource=c:\\Temp\\source.xlsx;Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";"; 

//code to read the content of format file 
OleDbConnection con = new OleDbConnection(Connection); 
OleDbCommand command = new OleDbCommand(); 

DataTable dt = new DataTable(); 
OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Tabelle1$]", con); 

myCommand.Fill(dt); 
Console.Write(dt.Rows.Count); 

我获得TA校正从输出计数,但我有2个问题:

1.如何做select select语句(如何访问行)?

select * from [Tabelle1$] where A = '123' (A being an existing Excel row) 

将抛出一个错误提错参数...

2.可有人为我提供的教程链接或简短的样本如何访问数据?

+0

请务必阅读由尤金联很好的教程。你会意识到为什么A ='123'不起作用(但是转动HDR =否,并写入WHERE F1 ='123'将) – nantito 2011-05-04 16:24:01

+0

我得到它与F1的工作,但不明白为什么A不工作,以及如何访问默认表名... – 2011-05-05 07:45:50

+0

如果有HeaDer行,HDR表示。如果设置为“是”,则表示不是设置自动“F1,F2 ...”,而是将第一行的单元格作为列名称的指示符。 – nantito 2011-05-05 15:05:23

回答

19

请参考下面的示例代码:

private DataTable LoadXLS(string strFile, String sheetName, String column, String value) 
{ 
    DataTable dtXLS = new DataTable(sheetName); 

    try 
    { 
     string strConnectionString = ""; 

     if(strFile.Trim().EndsWith(".xlsx")) { 

      strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile); 

     } else if(strFile.Trim().EndsWith(".xls")) { 

      strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile); 

     } 

     OleDbConnection SQLConn = new OleDbConnection(strConnectionString); 

     SQLConn.Open(); 

     OleDbDataAdapter SQLAdapter = new OleDbDataAdapter(); 

     string sql = "SELECT * FROM [" + sheetName + "$] WHERE " + column + " = " + value; 

     OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn); 

     SQLAdapter.SelectCommand = selectCMD; 

     SQLAdapter.Fill(dtXLS); 

     SQLConn.Close(); 
    } 

    catch (Exception e) 
    { 
     Console.WriteLine(e.ToString()); 
    } 

    return dtXLS; 

} 
+0

为您工作? – 2012-06-13 06:26:51

+0

我可以在哪里下载oledb提供商? – 2012-10-12 09:26:37

+3

从http://www.microsoft.com/zh-CN/download/details.aspx?id=13255下载。 32位或64位取决于操作系统。 – 2012-10-12 12:05:59