excel遇到的問題---外部表不是預期的格式。/csv 文件導入讀取問題


 檢查出了錯誤,Excel版本問題,Exce連接字符串版本是office2003的 ,更改為Excel2007版本則正常導入。 

 string strConn = 
 "Provider=Microsoft.Ace.OleDb.12.0;" + "data source
 =" + Server.MapPath("ExcelFiles/Mydata2007.xlsx") + ";
 Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'"; 
 //此連接可以操作.xls與.xlsx文件 (支持Excel2003 和 Excel2007 的連接字符串)

使用OLEDB讀取excel和csv文件

/// <summary>
        /// 使用OLEDB讀取excel和csv文件
        /// </summary>
        /// <param name="path">文件所在目錄地址</param>
        /// <param name="name">文件名</param>
        /// <returns></returns>
        public static DataSet ReadFile(string path, string name)
        {
            if (string.IsNullOrWhiteSpace(path) || string.IsNullOrWhiteSpace(name) || !File.Exists(path+name))
                return null;
            // 讀取excel 
            string connstring = string.Empty;
            string strSql = string.Empty;
            if (name.EndsWith(".xls") || name.EndsWith(".xlsx"))
            {
                connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + name + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';";
                strSql = "select * from [sheet1$]";
            }
            // 讀取csv文件
            else if (name.EndsWith(".csv"))
            {
                connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='text;HDR=YES;FMT=Delimited';";
                strSql = "select * from " + name;
            }
            else
            {
                return null;
            }
            DataSet ds = null;
            OleDbConnection conn = null;
            try
            {
                conn = new OleDbConnection(connstring);
                conn.Open();
                OleDbDataAdapter myCommand = null;

                myCommand = new OleDbDataAdapter(strSql, connstring);
                ds = new DataSet();
                myCommand.Fill(ds, "table1");
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
            }
            return ds;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM