Upload/Upload代码
1 public ActionResult Upload(HttpPostedFileBase httpPostedFileBase)
2 {
3 HttpPostedFileBase httpPostedFile = Request.Files["files"];
4 string FileName, SavePath;
5 if(httpPostedFile == null || httpPostedFile.ContentLength <= 0)
6 {
7 ViewBag.error = "文件不能为空";
8 return View();
9 }
10 else
11 {
12 string ExcelName = Path.GetFileName(httpPostedFile.FileName);
13 string Extention = System.IO.Path.GetExtension(ExcelName);
14 string NoExtention = Path.GetFileNameWithoutExtension(ExcelName);
15 string FileType = ".xlsx";
16 FileName = NoExtention + Extention;
17 if (!FileType.Contains(Extention))
18 {
19 ViewBag.error = "只能导入xlsx格式的文件";
20 return View();
21 }
22 string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
23 SavePath = Path.Combine(path, FileName);
24 httpPostedFile.SaveAs(SavePath);
25 }
26 string Result = string.Empty;
27 string strConn = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + SavePath + ";" + "Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
28 OleDbConnection oleDbConnection = new OleDbConnection(strConn);
29 oleDbConnection.Open();
30 OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter("select * from [生产计划$]", strConn);
31 DataSet dataSet = new DataSet();
32 try
33 {
34 oleDbDataAdapter.Fill(dataSet, "Results");
35 oleDbConnection.Close();
36 DataTable dataTable = dataSet.Tables["Results"];
37 }
38 catch(InvalidCastException e)
39 {
40
41 }
42 SprayTable = dataSet.Tables["Results"].DefaultView.ToTable();
43 //将部件数据放到数据库里
44 //Spray spray = new Spray();
45 //for(int i = 0; i < SprayTable.Rows.Count; i++)
46 //{
47 // spray.MaterialGroupNum = SprayTable.Rows[i][20].ToString();
48 // spray.MaterialName = SprayTable.Rows[i][7].ToString().Replace("(", "(").Replace(")", ")");//不管用
49 // spray.PlanNum = Convert.ToInt32(SprayTable.Rows[i][12].ToString());
50 // layuiContext.Sprays.Add(spray);
51 // layuiContext.SaveChanges();
52 //}
53 return View(SprayTable); //将excel表里的数据存储到了SprayTable里。
54 }
./Controllers/UploadController.cs