.Net Web项目实现:导入Excel表,向数据库增加记录

前端相关

  界面样式:

 

   前端代码:在Index.cshtml

1    <form method="post" action="/Home/Upload">
2         <input id="fileUpload" type="file" name="file"  />
3         <div class="input-group pull-right">
4             <button type="submit" id="cc">提交</button>          
5         </div>
6     </form>

数据库相关

  数据库名:student   表名:stuinfo

  

  进行插值的Excel表

  

 

 

 后端代码

  在HomeController.cs

 1 using NPOI.XSSF.UserModel;
 2 using System;
 3 using System.IO;
 4 using System.Collections.Generic;
 5 using System.Data;
 6 using System.Data.SqlClient;
 7 using System.Linq;
 8 using System.Web;
 9 using System.Web.Mvc;
10 
11 namespace excel316.Controllers
12 {
13     public class HomeController : Controller
14     {
15         public ActionResult Index()
16         {
17             return View();
18         }
19 
20         
21         [HttpPost]
22         public ActionResult Upload()
23         {
24             var ExcelTable = new DataTable();
25             var ExcelConnectionString = "Data Source=.; Initial Catalog=student;User ID=sa;Password=Admin12345";//student是数据库名
26             var Adp = new SqlDataAdapter("select * from stuinfo", ExcelConnectionString);
27             var DataCopier = new SqlBulkCopy(ExcelConnectionString) { DestinationTableName = "stuinfo" };//stuinfo是表名
28             Adp.FillSchema(ExcelTable, SchemaType.Source);
29 
30             string path = Request.Form.Get("file");//获取前端控件中所选文件的路径,file是<input>中的name值
31 
32             var wk = new XSSFWorkbook(System.IO.File.OpenRead(path));
33             var st = wk.GetSheetAt(0);
34             for(var RowIndex = 1; RowIndex<= st.LastRowNum; RowIndex++)
35             {
36                 var TableNewRow = ExcelTable.NewRow();
37                 var TempRow = st.GetRow(RowIndex);
38                 //数据表中有三个字段,第一个字段是ID。主键,自增,不需要我们给这个字段赋值
39                 //Excel表中只有两个字段
40                 //所以TableNewRow从下标1开始赋值,赋的值是Excel表的第0个字段
41                 TableNewRow[1] = TempRow.Cells[0].StringCellValue;
42                 TableNewRow[2] = TempRow.Cells[1].NumericCellValue;
43                 ExcelTable.Rows.Add(TableNewRow);
44             }
45             DataCopier.WriteToServer(ExcelTable);
46             Console.WriteLine("数据上传成功");
47             return View();
48         }
49     }
50 }

 

 

 

posted @ 2023-03-17 10:51  胡烙懿  阅读(131)  评论(0编辑  收藏  举报