Sheet1$是Excel默认的第一个表名,如果改动:select * from [Sheet1$]"将查询失败,因此应根据选择自动获取excel表名:
OpenFileDialog ofd = new OpenFileDialog(); //选择文件路径
ofd.Title = "Excel文件";
ofd.FileName = "";
ofd.Filter = "Excel文件(*.xls)| *.xls";
string Path = ofd.FileName;
string tableName = ""; 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 sTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
tableName = sTable.Rows[][].ToString().Trim(); for (int i = ; i < sTable.Rows.Count; i++)
{
schemaTable.Rows[i][].ToString().TrimStart('\'').Trim('\'', '$');
} string strExcel = "select * from [" + tableName + "]";
OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn);
DataSet ds = new DataSet();
DataTable table1 = new DataTable();
myCommand.Fill(table1);
//==========最后绑定
dataGridView1.DataSource = table1;