您的位置:首页 > 其它

将Excel导入DataGridView 中的"select * from [Sheet1$]"中[ ]里面表单名的动态获取

2014-04-27 17:35 507 查看
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[0][2].ToString().Trim();

for (int i = 0; i < sTable.Rows.Count; i++)
{
schemaTable.Rows[i][2].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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: