.net导入Excel文件返回DataSet数据集

        #region 获取数据集
        protected DataSet GetDataSet(string filePath)
        {
            //2010以前版本连接字符串  
            //string Connstr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + filePath + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'");    

            //IMEX=1 一共有三种模式 0表示导出 1 导入 2表示混合模式 在读取Excel数据有金额类型的后面带小数点最好去掉IMEX属性    
            //HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES  
            string Connstr2010 = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + Server.MapPath("~/") + filePath + "';Extended Properties='Excel 12.0;HDR=NO'");
            OleDbConnection Conn = new OleDbConnection(Connstr2010);
            //创建ArrayList对象 存放所有sheetname      
            ArrayList sheetNamelist = new ArrayList();
            DataSet dsExcel = new DataSet();
            try
            {
                if (Conn.State == ConnectionState.Closed)//检测conn是否处于开启状态
                {
                    Conn.Open();
                }
                DataTable dtExcelSchema = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });


                string sheetName = string.Empty;

                for (int j = 0; j < dtExcelSchema.Rows.Count; j++)
                {

                    sheetName = dtExcelSchema.Rows[j]["TABLE_NAME"].ToString();
                    //sheet名称   
                    if (sheetName.ToLower().IndexOf("database") != -1)
                        continue;
                    else
                        sheetNamelist.Add(sheetName);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString(), ex);
            }
            finally
            {
                Conn.Close();
            }
            try
            {
                string strSQL = string.Empty;
                for (int i = 0; i < sheetNamelist.Count; i++)
                {

                    strSQL = "select * from [" + sheetNamelist[i].ToString() + "]";
                    OleDbDataAdapter da = new OleDbDataAdapter(strSQL, Conn);
                    DataTable dtExcel = new DataTable(sheetNamelist[i].ToString());
                    da.Fill(dtExcel);

                    dsExcel.Tables.Add(dtExcel);
                }

                return dsExcel;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString(), ex);
                return null;
            }
            finally
            {

            }
        }
        #endregion

发布了42 篇原创文章 · 获赞 4 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章