private void btnSelectFile_Click(object sender, EventArgs e) { //打开文件对话框。 OpenFileDialog openFile = new OpenFileDialog(); //后缀名。 openFile.Filter = "Excel文件(*.xls,*.xlsx)|*.xls;*.xlsx"; if (openFile.ShowDialog() == DialogResult.OK) { try { //文件名包含路径 string filename = openFile.FileName; txtExcelName.Text = filename; //sql语句 string sql = "select * from [Sheet1$]"; //数据库连接字符串 string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + filename; //如果是2007格式 if (filename.ToUpper().EndsWith("XLSX")) { connStr= "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0;data source=" + filename; } DataSet ds = SqlHelper.ExecuteDataset(connStr, sql, CommandType.Text); dgvCurrent.DataSource = ds.Tables[0].DefaultView; lblcount.Text = ds.Tables[0].Rows.Count.ToString(); } catch (Exception err) { MessageBox.Show("错误:" + err.Message); } } }