码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2014-04-28 04:29:08      阅读:1060      评论:0      收藏:0      [点我收藏+]

标签:datagridview   com   class   http   blog   code   div   img   style   java   javascript   

Sheet1$是Excel默认的第一个表名,如果改动:select * from [Sheet1$]"将查询失败,因此应根据选择自动获取excel表名:

bubuko.com,布布扣
 1 OpenFileDialog ofd = new OpenFileDialog();  //选择文件路径
 2     ofd.Title = "Excel文件";
 3     ofd.FileName = "";
 4     ofd.Filter = "Excel文件(*.xls)| *.xls";
 5 string Path = ofd.FileName;
 6 string tableName = "";
 7 
 8 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
 9 OleDbConnection conn = new OleDbConnection(strConn);
10 conn.Open();
11 System.Data.DataTable sTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
12 tableName = sTable.Rows[0][2].ToString().Trim();
13 
14 for (int i = 0; i < sTable.Rows.Count; i++)
15 {
16     schemaTable.Rows[i][2].ToString().TrimStart(\‘).Trim(\‘, $);
17 }
18 
19 string strExcel = "select * from [" + tableName + "]";
20 OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn);
21 DataSet ds = new DataSet();
22 DataTable table1 = new DataTable();
23 myCommand.Fill(table1);
24 //==========最后绑定
25 dataGridView1.DataSource = table1;
bubuko.com,布布扣

 

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

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

标签:datagridview   com   class   http   blog   code   div   img   style   java   javascript   

原文地址:http://www.cnblogs.com/qiernonstop/p/3694925.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!