把excel文档中的内容读取到dataset中

如何把excel文档中的内容读取到dataset中呢?我查询了一些资料,并亲自试用,以下代码均通过vs2010编译:

以下是实现该功能的一个函数,直接调用即可:

函数的参数说明:filepath是excel所在的全路径,tablename是EXCEL文档里的一个表名,一般为sheet1

 private DataSet xsldata(string filepath, string tablename)       

 { 
             string strCon = ""; 
             string filemode = filepath.Substring(filepath.Length - 4, 4); 
                if (filemode == ".xls") 
                 { 
                     strCon = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filepath + ";" + "Extended Properties='Excel 8.0;IMEX=1'";  //excel2003
                } 
                else if (filemode == "xlsx") 
             { 
                 strCon = "Provider=Microsoft.Ace.OLEDB.12.0;" + "Data Source=" + filepath + ";" + "Extended Properties='Excel 12.0;IMEX=1'";  //excel2007
             } 
             System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection(strCon); 
             string strCom = "SELECT * FROM [" + tablename + "$]"; 
                Conn.Open(); 
             System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, Conn); 
             DataSet ds = new DataSet(); 
             DataGridView dataGridView = new DataGridView(); 
             myCommand.Fill(ds, "[" + tablename + "$]"); 
                dataGridView.DataSource = ds.Tables[0]; 
             Conn.Close(); 
             return ds; 
         }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值