第一种
try { string filePath = ""; if (UploadFile1.Value == "") { Page.RegisterStartupScript("", "<script>alert('请选择要上传的文件!');</script>"); return; } else { filePath = UploadFile1.Value; string name = filePath.Substring(filePath.LastIndexOf("\\") + 1).ToString(); filePath = path + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss") + "_" + name; string exp = name.Substring(name.LastIndexOf(".") + 1); UploadFile1.PostedFile.SaveAs(filePath); string strCon = ""; if (exp != "xls" && exp != "XLS" && exp != "xlsx" && exp != "XLSX") { Page.RegisterStartupScript("error", "<script>alert('文件格式不对!');</script>"); } else { if (exp == "xls" || exp == "XLS") { strCon = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0"; } else { strCon = "Provider=Microsoft.ACE.OleDb.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0"; } using(OleDbConnection myConn = new OleDbConnection(strCon)){ myConn.Open(); if (name != "") { DataTable schemaTable = myConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); //获取表名 if (schemaTable.Rows.Count > 0) { string tablename = schemaTable.Rows[0]["TABLE_NAME"].ToString();//获到Execl表名 string sql = "select * from [" + tablename + "]"; OleDbDataAdapter da = new OleDbDataAdapter(sql, myConn); DataSet ds = new DataSet(); IList<Book> PersonList = new List<Book>(); da.Fill(ds);//将要导入的Execl表内容填充到DataSet数据集中 int r = ds.Tables[0].Rows.Count; if (r > 0)//判断Execl表是否有内容 { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { Book entity = new Book(); #region 需要导入的字段 entity.No = ds.Tables[0].Rows[i]["编号"].ToString().Trim(); entity.BookName = ds.Tables[0].Rows[i]["书名"].ToString().Trim(); entity.Author = ds.Tables[0].Rows[i]["作者"].ToString().Trim(); entity.Price = ds.Tables[0].Rows[i]["价格"].ToString().Trim(); #endregion _BookBO.Save(entity); } } } } } } } } catch (Exception ex) { Response.Write(ex.Message); }