private void btnSelectFile_Click(object sender, EventArgs e) { dictionary.Clear(); dtAll.Clear(); //打开文件对话框。 OpenFileDialog openFile = new OpenFileDialog(); openFile.Multiselect = true; //后缀名。 openFile.Filter = "Excel文件(*.xls,*.xlsx)|*.xls;*.xlsx"; if (openFile.ShowDialog() == DialogResult.OK) { btnExport.Text = "导入"; btnExport.Enabled = true; try { //文件名包含路径 string[] filenames = openFile.FileNames; for (int i = 0; i < filenames.Length; i++) { string filename = filenames[i]; //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; } DataTable dt = SqlHelper.ExecuteDataset(connStr, sql, CommandType.Text).Tables[0]; string filename2 = filename.Substring(filename.LastIndexOf('\\') + 1); dictionary.Add(filename2, dt); if (i == 0) { dtAll = dt.Copy(); } else { foreach (DataRow dr in dt.Rows) { dtAll.ImportRow(dr); } } } string filenames2 = string.Empty; foreach (var key in dictionary.Keys) { filenames2 += key + ","; } txtExcelName.Text = filenames2; dgvCurrent.DataSource = dtAll.DefaultView; lblcount.Text = dtAll.Rows.Count.ToString(); } catch (Exception err) { MessageBox.Show("错误:" + err.Message); } } else { txtExcelName.Text = string.Empty; btnExport.Enabled = false; } }