今天分享一下,C#里怎么把Excel数据导入道DataSet然后进行处理。
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "打开";
ofd.Filter = "xlsx文件|*.xlsx|xls文件|*.xls|xlsm文件|*.xlsm"; //这里来筛选能打开的文件类型
if (ofd.ShowDialog() == DialogResult.OK)
{
string connection = "Provider = Microsoft.Ace.OleDb.12.0 ; Data Source = " + ofd.FileName + ";Extended Properties=Excel 12.0";
OleDbConnection thisconnection = new OleDbConnection(connection);
string command = "select * from [sheet1$]"; //我这里是查询Excel里的sheet1表格数据
thisconnection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(command, thisconnection);
DataSet ds = new DataSet();
adapter.Fill(ds, "[sheet1$]"); //把读取出来的表格数据赋给DataSet
thisconnection.Close();
if (ds.Tables[0].Rows.Count < 1)
{
MessageBox.Show("表中无数据");
return;
}
else
{
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
//这里你就可以进行对读出来的Excel数据进行相应的处理
}
}
}