C#从XLS检索数据
我有一个类ParseXLS(string名称,stringdriveLincence,string性)
我的.xls如下所示:
名称| 驾驶执照| 性别
A – Y – M
B – N – F
我想读一个大的.xls,并把所有这些数据放在我的类中。 阅读我使用的.xls:
OleDbDataReader reader; OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + xlsFilePath + ";Extended Properties=Excel 8.0"); OleDbCommand command = new OleDbCommand("select * from [sheet1$]", con); con.Open();
但我不知道如何获得一个List或ObservableCollection ..我发现很多硬解决scheme,很多的代码,并不清楚,我希望有人可以帮助我一个简单的解决scheme。
提前致谢
您可以将数据加载到DataTable
:
var results = new DataTable(); using(var con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + xlsFilePath + ";Extended Properties=Excel 8.0")) { var command = new OleDbCommand("select * from [sheet1$]", con); con.Open(); var adapter = new OleDbDataAdapter(command); adapter.Fill(results); }
从那里,循环的结果和使用的数据,但是你需要:
foreach(DataRow row in results) { var name = row["name"].ToString(); var driversLicense = row["Drive Licence"].ToString(); var sex = row["Sex"].ToString(); //Do what you need }
另一种方法是使用像EPPlus这样的第三方库。