excel遇到的问题---外部表不是预期的格式。/csv 文件导入读取问题
检查出了错误,Excel版本问题,Exce连接字符串版本是office2003的 ,更改为Excel2007版本则正常导入。
1 2 3 4 5 | 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文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | /// <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; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步