OpenFileDialog openFD = new OpenFileDialog(); openFD.FileName = ""; openFD.Filter = "xls|*.xls|xlsx|*.xlsx"; openFD.Title = "选择更新文件"; openFD.Multiselect = false; if (openFD.ShowDialog() == DialogResult.OK) { this.tbSelectFile.Text = openFD.FileName; //读取Excel pDataSet.Clear();
//成功的关键在于下面这句话,网上有很多不同版本,但这个是亲测可用的。 string strConn = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + openFD .FileName + ";" + "Extended Properties=Excel 8.0;"; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); string strExcel = ""; OleDbDataAdapter myCommand = null; strExcel = "select * from [sheet1$]"; myCommand = new OleDbDataAdapter(strExcel, strConn); myCommand.Fill(pDataSet , "table1"); conn.Close(); }