将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;
相关文章推荐
- 黑马程序员_java基础_语法基础&流程控制
- Linux ffmpeg命令的使用
- linux下编译ffmpeg
- Shallow Size 和 Retained Size
- 福州大学第十一届程序设计竞赛
- 基于用例点来度量软件规模并管理进度 之结束语
- mysql常用查询:group by,左连接,子查询,having where
- 【原创】python模拟腾讯网页登录
- 观察者模式
- Java 并发(一)——线程和同步
- /storage/sdcard, /sdcard, /mnt/sdcard 三者的区别
- 实验:添加AXI IP到设计
- iOS MapKit导航及地理转码辅助类
- ES mapping设置
- 使用CKRule实现PVC配方计算
- 【ruby】ruby 动态方法总结
- 20060207-Spatial transformations: Affine
- 忘记oracle的sys用户密码怎么修改
- sizeof与strlen的区别与联系
- window8下为Python33安装BeautifulSoup