上传Excel文件,出现错误:上传失败,没有可用的错误消息,结果代码:E_FAIL(0x80004005)
#region 取得文件后缀 /// <summary> /// 取得文件后缀 /// </summary> /// <param name="filename">文件名称</param> /// <returns></returns> public static string GetFileExtends(string filename) { string ext = null; if (filename.IndexOf('.') > 0) { string[] fs = filename.Split('.'); ext = fs[fs.Length - 1]; } return ext; } #endregion #region 获取链接字符串 /// <summary> /// 获取链接字符串 /// </summary> /// <param name="filepath">相对路径</param> /// <returns>链接字符串</returns> private static string getconstring(string filepath) { string constring; if (filepath.EndsWith(".xls")) { // Excel 97-2003 constring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES;IMEX=1'"; } else { // Excel 2007 constring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0 Xml;HDR=YES;'"; } return string.Format(constring, System.Web.HttpContext.Current.Server.MapPath(filepath)); } #endregion #region 读取excel表格sheet的名称 /// <summary> /// 读取excel表格sheet的名称 /// </summary> /// <param name="filepath">相对路径</param> /// <returns>excel表格sheet的名称数组</returns> public static string[] getexcelsheetnames(string filepath) { using (OleDbConnection con = new OleDbConnection(getconstring(filepath))) { con.Open(); DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); con.Close(); if (dt == null) { return null; } string[] excelsheetnames = new string[dt.Rows.Count]; int i = 0; foreach (DataRow dr in dt.Rows) { excelsheetnames[i++] = dr["table_name"].ToString(); } return excelsheetnames; } } #endregion #region 读取excel文件 /// <summary> /// 读取excel文件 /// </summary> /// <param name="filepath">相对路径</param> /// <param name="sheetname">查询Excel表格sheet的名称</param> /// <returns>DataTable</returns> public static DataTable readexcel(string filepath, string sheetname) { using (OleDbConnection con = new OleDbConnection(getconstring(filepath))) { if (string.IsNullOrEmpty(sheetname)) { sheetname = getexcelsheetnames(filepath)[0];//如果Excel表格sheet的名称为空,给个默认值 } using (OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}]", sheetname), con)) { DataTable dt = new DataTable(); con.Open(); oda.Fill(dt); con.Close(); return dt; } } } #endregion
office自带的dll不好用,不同的版本有兼容问题,用NPOI,读写轻松解决
贴代码看看,应该是由于excel版本问题导致的错误