读取Excel文件中的数据

时间:2021-07-30 10:02:57

string strSource = File1.Value;

   string ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strSource + ";Extended Properties=Excel 8.0";
   string query = "SELECT * FROM [Sheet1$]";//Sheet1表示表

   OleDbCommand oleCommand = new OleDbCommand(query, new OleDbConnection(ConnStr));
   OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCommand);
   DataSet myDataSet = new DataSet();

   // 将 Excel 的[Sheet1]表内容填充到 DataSet 对象
   oleAdapter.Fill(myDataSet, "[Sheet1$]");

   // 数据绑定
   DataGrid1.DataSource = myDataSet;
   DataGrid1.DataMember = "[Sheet1$]";
   DataGrid1.DataBind();