c#读取excel到dataset

    public DataSet TransExcelToDataSet(string fileName, List<string> sheetNames)
        {
            OleDbConnection objConn =null;
            DataSet data =new DataSet();

            //创建读取excel连接
            string strConn ="Provider=Microsoft.Jet.OleDb.4.0;"+"data source="+ fileName
                +";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
            try
            {

                objConn =new OleDbConnection(strConn);
                using (objConn)
                {
                    OleDbDataAdapter sqlada =null;
                    //遍历从配置文件中读取的sheet名称
                    foreach (string sheetName in sheetNames)
                    {
                        if (!string.IsNullOrEmpty(sheetName))
                        {
                            string strSql ="select * From ["+ sheetName.Trim() +"$]";
                            sqlada =new OleDbDataAdapter(strSql, objConn);
                            //填充dataset
                            sqlada.Fill(data, sheetName);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                thrownew Exception("将excel中指定sheet内容读入dataset出错!"+ e.Message +" strConn: "+ strConn +" ; fileName:"+ fileName);
                //throw e;
            }
            finally
            {
                if (objConn !=null)
                {
                    objConn.Dispose();
                    objConn.Close();
                }
               
                GC.Collect();
            }
            return data;
        }

 

posted @ 2018-07-18 11:31  恋上微笑的天使  阅读(888)  评论(0编辑  收藏  举报