对于新版本,和老版本Excel创建的xls(xlsx)版本,需要用不同的连接字符串,自行选择
1 2 3 4 5
| string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
string conStr="Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| string fileName = "装备信息.xls";
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
OleDbConnection connection = new OleDbConnection(conStr);
connection.Open();
string sql = "select * from [Sheet1$]";
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, connection);
DataSet ds = new DataSet();
adapter.Fill(ds);
connection.Close();
DataTableCollection tableCollection= ds.Tables;
DataTable table = tableCollection[0];
DataRowCollection rows= table.Rows;
foreach (DataRow row in rows) { for (int i = 0; i < 7; i++) { Console.Write("{0}",row[i]); } Console.WriteLine(); }
|
输出内容:
参考:SikiC#高级课程
TonyChenn
2018.9.25