日期:2014-05-18 浏览次数:20839 次
if (FileUpload1.FileName == "") { Page.RegisterStartupScript("是","<script>alert('请选择文件');</script>"); return null; } string fileExtenSion; fileExtenSion = Path.GetExtension(FileUpload1.FileName); if (fileExtenSion.ToLower() != ".xls" && fileExtenSion.ToLower() != ".xlsx") { Page.RegisterStartupScript("是", "<script>alert('上传文件格式不正确!');</script>"); return null; } try { string FileName = "App_Data/" + Path.GetFileName(FileUpload1.FileName); if (File.Exists(Server.MapPath(FileName))) { File.Delete(Server.MapPath(FileName)); } FileUpload1.SaveAs(Server.MapPath(FileName));
private DataTable xsldata() { if (FileUpload1.FileName == "") { Page.RegisterStartupScript("是","<script>alert('请选择文件');</script>"); return null; } string fileExtenSion; fileExtenSion = Path.GetExtension(FileUpload1.FileName); if (fileExtenSion.ToLower() != ".xls" && fileExtenSion.ToLower() != ".xlsx") { Page.RegisterStartupScript("是", "<script>alert('上传文件格式不正确!');</script>"); return null; } try { string FileName = "App_Data/" + Path.GetFileName(FileUpload1.FileName); if (File.Exists(Server.MapPath(FileName))) { File.Delete(Server.MapPath(FileName)); } FileUpload1.SaveAs(Server.MapPath(FileName)); //HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES string connstr2003 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(FileName) + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; string connstr2007 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(FileName) + ";Extended Properties=\"Excel 12.0;HDR=YES\""; OleDbConnection conn; if (fileExtenSion.ToLower() == ".xls") { conn = new OleDbConnection(connstr2003); } else { conn = new OleDbConnection(connstr2007); } conn.Open(); string sql = "select * from [Sheet1$]"; OleDbCommand cmd = new OleDbCommand(sql, conn); DataTable dt = new DataTable(); OleDbDataReader sdr = cmd.ExecuteReader(); dt.Load(sdr); sdr.Close(); conn.Close(); //删除服务器里上传的文件 if (File.Exists(Server.MapPath(FileName))) { File.Delete(Server.MapPath(FileName)); } return dt; } catch (Exception e) { return null; } } protected void Button1_Click(object sender, EventArgs e) { try{ DataTable dt = xsldata(); //dataGridView2.Da