把Excel中的数据导入gridView显示,再导入数据库
2012-02-11 21:22 javaspring 阅读(241) 评论(0) 编辑 收藏 举报把Excel中的数据导入gridView显示,再导入数据库
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.OleDb;
//创建一个临时DataTable,为了把Excel中的数据导入gridView后再导入数据库。 private static DataTable dtTemp; /// <summary> /// 把Excel导入Gridview,首先把文件上传到服务器 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnImport_Click(object sender, EventArgs e) { //导入Excel文件 //检查文件是否存在 //HasFile用来检查上传文件控件FileUpload是否有指定文件 if (FileUpload1.HasFile == false) { Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('请您选择Excel文件! ');</script>"); return;//当无文件时,返回 } string filename = DateTime.Now.ToString("yyyymmddhhMMss") + FileUpload1.FileName; //获取Execle文件名 DateTime日期函数 string savePath = Server.MapPath(("../Doc/") + filename);//Server.MapPath 获得虚拟服务器相对路径 //如果已经存在就清空 ClearFile(Server.MapPath("../Doc/")); FileUpload1.SaveAs(savePath); //SaveAs 将上传的文件内容保存在服务器上 DataTable dt = createDataSource(savePath); if (dtTemp == null) { dtTemp = new DataTable(); dtTemp = dt; } GridView1.DataSource = dt; GridView1.DataBind(); } /// <summary> /// 从gridview导入数据库 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSubmit_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt = dtTemp; for (int i = 0; i < dt.Rows.Count; i++) { //导入数据库的代码省略 } Response.Write("<script>alert('添加成功!!')</script>"); } /// <summary> /// 将路径下的Excel文件转换为DataTable类型的数据源 /// </summary> /// <param name="strPath">Excel路径</param> /// <returns></returns> private DataTable createDataSource(string strPath) { string strCon; strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strPath + ";Extended Properties=Excel 8.0"; OleDbConnection con = new OleDbConnection(strCon); OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con); DataTable dt = new DataTable(); da.Fill(dt); return dt; } /// <summary> /// 将Excel文件暂存到服务器端的一个文件夹中,用这个方法删除掉 /// </summary> /// <param name="FilePath">Excel路径</param> private void ClearFile(string FilePath) { String[] files = System.IO.Directory.GetFiles(FilePath); if (files.Length > 5) { for (int i = 0; i < 5; i++) { try { System.IO.File.Delete(files[i]); } catch { } } } }