(原创博客,转载请标明出处)
目标是将excel文档中的内容放入到一个dataset中
1.在客户端上的各种验证(是否有文件,文件后缀等等),取出excel中内容之后删除服务器上临时上传的文件
//文件上传 protected void btnFileUpload_Click(object sender, EventArgs e) { try { //将用户导入的excel存入dt if (!this.fupload_Excel.HasFile) { ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>alert('该文件不存在或无内容,请重新选择!');</script>"); return; } else { //先确保已经选择了导入记录的燃料类型(项目需要的一个判断) //if (ddl_fuel_type.SelectedItem.Text == "-请选择燃料类型-") //{ //ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>alert('请先选择燃料类型!');</script>"); //return; //} //返回指定字符串的扩展名,并验证 string fileException = System.IO.Path.GetExtension(this.fupload_Excel.FileName).ToLower(); if (fileException != ".xls") { ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>alert('对不起,只能上传后缀名为.xls的文件!');</script>"); } else { string filename = Server.MapPath("../") + @"PARAMETER_mannager\fileForUpload\" + this.fupload_Excel.FileName.ToString();// + System.DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls" fupload_Excel.SaveAs(filename); //注意一定要释放内存 fupload_Excel.Dispose(); dt = GetListFromExcel(filename, "Sheet1"); //删除所选文件 FileInfo file = new FileInfo(filename); file.Delete(); if (dt == null) { ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>alert(\"导入失败,请按照模板及提示修改后重新导入!\");</script>"); } } } } catch (Exception) { ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>alert(\"导入失败,请按照模板及提示修改后重新导入!\");</script>"); } }
2.将已上传到服务器的临时Excel文件中的内容写入到一个ds中(注意两点,其一,不可以是html格式的Excel文档;其二,sheetname要对应好!)
//导入excel表格时注意问题:表格不能是html格式,会提示格式错误。其次sheetName要对应上 public System.Data.DataTable GetListFromExcel(string filename, string sheetName) { string conn = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= {0};Extended Properties=Excel 8.0;", filename); OleDbConnection oleDbConnection = new OleDbConnection(conn); //sheetName为excel中表的名字,如:sheet1 string sql = string.Format("select * from [{0}$]", sheetName); OleDbCommand cmd = new OleDbCommand(sql, oleDbConnection); OleDbDataAdapter ad = new OleDbDataAdapter(cmd); DataSet ds = new DataSet(); try { //将excel中的内容导入到ds中 ad.Fill(ds); //除去关键字段的空格,保证容错性 for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { ds.Tables[0].Rows[i]["SAP码第六位第七位(必填)"] = ds.Tables[0].Rows[i]["SAP码第六位第七位(必填)"].ToString().Trim(); ds.Tables[0].Rows[i]["车辆型号(必填)"] = ds.Tables[0].Rows[i]["车辆型号(必填)"].ToString().Trim(); } return ds.Tables[0]; } catch (Exception ex) { Response.Write("<script>alert('导入失败,请按照模板及提示修改后重新导入!')</script>"); return null; } }