public string SaveUploadExcel(HttpPostedFile hpf)//验证Excel文件的正确性 { //检查文件格式各文件大小是否有效 if(hpf == null || hpf.ContentLength < 1 || System.IO.Path.GetExtension(hpf.FileName).ToLower() != ".xls") { throw new InnerException("文件上传失败或文件格式不正确。!"); }
//保存文件 try { string fileFullName = MakeFileName(); hpf.SaveAs(fileFullName); return fileFullName; } catch//(Exception ex) { throw new InnerException("保存文件失败。");// + ex.Message); } }
public string MakeFileName()//生成唯一文件名的Excel文件 { string filePath = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath) +"\\uploadFiles\\PlanExcel"; if(!Directory .Exists(filePath)) Directory.CreateDirectory(filePath); string fileName = Convert.ToString(HttpContext.Current.Session["UserID"]) + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
return filePath + "\\" + fileName; }
public DataTable ReadNoHeadExcelData(string fileFullName)//读取Excel文件最后返回一个DataTable,可以在返回DataTable后对这个DataTable进行检验! { string excelNoHeadConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1;\"";//连接字符串 OleDbConnection oleCn =new OleDbConnection(); try { string currConnStr = string.Format(excelNoHeadConnStr, fileFullName);//连接字符串 oleCn.ConnectionString = currConnStr; DataTable dt = new DataTable(); oleCn.Open(); string excelBookName = oleCn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null).Rows[0][2].ToString(); if(excelBookName!=string.Empty && excelBookName.Trim()!="") { string currSqlStr = string.Format(excelSqlStr, excelBookName);//sql字符串 OleDbCommand oleCmd = new OleDbCommand(currSqlStr, oleCn); OleDbDataAdapter oleDda = new OleDbDataAdapter(oleCmd); oleDda.Fill(dt); } oleCn.Close(); return dt; } catch { string errorMsg="Excel文件格式不对,请尝试用excel打开该文件检查内容并另存一下,确保成为正确的excel文件,再重新上传"; System.Web.HttpContext.Current.Response.Write("<script>alert('"+ errorMsg +"')</script>"); oleCn.Close(); return null; } }
|
请发表评论