.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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章