public void ExcelIntoDatagridView() { //打开一个文件选择框 OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "Excel文件"; ofd.FileName = ""; ofd.Filter = "Excel文件(*.xls)|*.xls"; try { if (ofd.ShowDialog() == DialogResult.OK) { string tableName = ""; if (arratlist != null) { arratlist.Clear(); } string Path = ofd.FileName; string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;"; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null); tableName = schemaTable.Rows[0][2].ToString().Trim(); for (int i = 0; i < schemaTable.Rows.Count; i++) { arratlist.Add(schemaTable.Rows[i][2].ToString().TrimStart('/'').Trim('/'', '$'));// } arratlist.Sort(); string strExcel = "Select * From [" + tableName + "]"; OleDbCommand cmd = new OleDbCommand(strExcel, conn); DataTable excelDt = new DataTable(); OleDbDataAdapter da = new OleDbDataAdapter(strExcel, conn); da.Fill(excelDt); conn.Close(); MessageBox.Show("excel 导入成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); if (excelDt != null) { dataGridView1.DataSource = excelDt; } } } catch (Exception ex) { MessageBox.Show("导入文件时出错,文件可能正被打开","提示"); } }