excel 資料讀取

taogchan發表於2012-12-24
        ///
        /// 讀取Excel文件
        ///

        /// 檔名稱
        /// 返回一個資料集
        public DataSet ExcelToDS(string Path)
        {
            string strConn = string.Empty;
            //= "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
            if (Path.ToLower().IndexOf(".xlsx") > 0)
            {
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + Path + "';Extended Properties='Excel 12.0;HDR=YES'";
            }
            if (Path.ToLower().IndexOf(".xls") > 0 && Path.EndsWith("xls"))
            {
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + Path + "';Extended Properties='Excel 8.0;HDR=YES;'";
            }

            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            string strExcel = "";
            OleDbDataAdapter myCommand = null;
            DataSet ds = null;
            strExcel = "select * from [sheet1$]";
            myCommand = new OleDbDataAdapter(strExcel, strConn);
            ds = new DataSet();
            myCommand.Fill(ds, "table1");
            conn.Close();
            return ds;
        }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22392018/viewspace-751570/,如需轉載,請註明出處,否則將追究法律責任。

相關文章