一、搭建环境
1.新建ASP.NET Core Web 应用程序
2.选择API
3.引用Swashbuckle.AspNetCore NuGet 包进行安装. Swashbuckle.AspNetCore 是一个开源项目,用于生成 ASP.NET Core Web API 的 Swagger 文档。
前端开发人员可在浏览器中访问此接口文档。
4.光引用此NuGet包是不行的,还要在Startup中添加并配置Swaage中间件
首先在ConfigureServices中写入以下代码:
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); #region services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "API文档", Version = "v1" }); }); #endregion }
然后在Configure中写入以下代码:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } #region app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); #endregion app.UseHttpsRedirection(); app.UseMvc(); }
5.右键项目生成XML文件,并在Startup中注册服务,用于读取这个XML文档,不然写的接口都不会显示出来.
引用NuGet包:Microsoft.Extensions.PlatformAbstractions
接着在Startup类ConfigureServices方法中,添加如下代码:
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); #region services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "API文档", Version = "v1" }); #region var basePath = PlatformServices.Default.Application.ApplicationBasePath; //MyImport.xml是我的项目生成XML文档的后缀名,具体的以你项目为主 var xmlPath = Path.Combine(basePath, "MyImport.xml"); c.IncludeXmlComments(xmlPath); #endregion }); #endregion }
OK ,现在可以新建一个控制器,写一个接口看看有没有效果
将地址栏修改一下
我们也可以在launchSettings.json中做一下更改,这样就不用每次都改浏览器地址栏了,如下:
二·、数据库新建表及项目中实体类的建立
--商品表 Create Table Commodity ( Cid int primary key identity(1,1),--主键,自增 Name varchar(50) not null,--商品名称 Price decimal(18,2) not null,--价格 [Type] varchar(50) not null,--商品类别 [Time] varchar(50) not null,--保质期 Remarks varchar(100)--备注 )
using SqlSugar; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyImport.Model { /// <summary> /// 商品类 /// </summary> public class Commodity { /// <summary> /// 主键Id /// </summary> [SugarColumn(IsNullable = false, IsPrimaryKey = true, IsIdentity = true)] public int Cid { get; set; } /// <summary> /// 商品名称 /// </summary> [SugarColumn(Length = 50, IsNullable = false)] public string Name { get; set; } /// <summary> /// 商品价格 /// </summary> [SugarColumn(IsNullable = false)] public double Price { get; set; } /// <summary> /// 商品类别 /// </summary> [SugarColumn(Length = 50, IsNullable = false)] public string Type { get; set; } /// <summary> /// 保质期 /// </summary> [SugarColumn(Length = 50, IsNullable = false)] public string Time { get; set; } /// <summary> /// 备注 /// </summary> [SugarColumn(Length = 100, IsNullable = true)] public string Remarks { get; set; } } }
三、代码编写
注:在写代码之前,先引用两个NuGet包:NPOI(这个包用来操作Excel)和SqlSugarCore(这是一个高性能的ORM框架,操作数据库更便捷)
可以在wwwroot文件下放入导入的excel模板
话不多说,贴代码:
[HttpGet] public async Task<FileResult> DownLoadExcelTemplate() { FileStream file = new FileStream(_hostingEnvironment.WebRootPath + "\files\excel\Template.xls", FileMode.Open, FileAccess.Read);//读入excel模板 HSSFWorkbook book = new HSSFWorkbook(file); System.IO.MemoryStream ms = new MemoryStream(); book.Write(ms); ms.Seek(0, SeekOrigin.Begin); string dt = DateTime.Now.ToString("yyyy-MM-dd"); string filename = "导入数据的excel模板" + dt + ".xls"; return File(ms, "application/vns.ms-excel", filename); }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MyImport.Model; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using SqlSugar; namespace MyImport.Controllers { [Route("api/[controller]")] [ApiController] public class MyCoreController : Controller { public MyCoreController() { } SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = "Data Source=LENOVO-PC;Initial Catalog=School;Integrated Security=True", DbType = SqlSugar.DbType.SqlServer, IsAutoCloseConnection = true }); /// <summary> /// 数据导入 /// </summary> /// <returns></returns> [HttpPost] public async Task<string> Import(IFormFile file) { string ReturnValue = string.Empty; //定义一个bool类型的变量用来做验证 bool flag = true; try { string fileExt = Path.GetExtension(file.FileName).ToLower(); //定义一个集合一会儿将数据存储进来,全部一次丢到数据库中保存 var Data = new List<Commodity>(); MemoryStream ms = new MemoryStream(); file.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); IWorkbook book; if (fileExt == ".xlsx") { book = new XSSFWorkbook(ms); } else if (fileExt == ".xls") { book = new HSSFWorkbook(ms); } else { book = null; } ISheet sheet = book.GetSheetAt(0); int CountRow = sheet.LastRowNum + 1;//获取总行数 if (CountRow - 1 == 0) { return "Excel列表数据项为空!"; } #region 循环验证 for (int i = 1; i < CountRow; i++) { //获取第i行的数据 var row = sheet.GetRow(i); if (row != null) { //循环的验证单元格中的数据 for (int j = 0; j < 5; j++) { if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0) { flag = false; ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。"; } } } } #endregion if (flag) { for (int i = 1; i < CountRow; i++) { //实例化实体对象 Commodity commodity = new Commodity(); var row = sheet.GetRow(i); if (row.GetCell(0) != null && row.GetCell(0).ToString().Trim().Length > 0) { commodity.Name = row.GetCell(0).ToString(); } if (row.GetCell(1) != null && row.GetCell(1).ToString().Trim().Length > 0) { commodity.Price = Convert.ToDouble(row.GetCell(1).ToString()); } if (row.GetCell(2) != null && row.GetCell(2).ToString().Trim().Length > 0) { commodity.Type = row.GetCell(2).ToString(); } if (row.GetCell(3) != null && row.GetCell(3).ToString().Trim().Length > 0) { commodity.Time = row.GetCell(3).ToString().ToString(); } if (row.GetCell(4) != null && row.GetCell(4).ToString().Trim().Length > 0) { commodity.Remarks = row.GetCell(4).ToString(); } else { commodity.Remarks = "暂无"; } Data.Add(commodity); } var data = db.Insertable<Commodity>(Data).ExecuteCommand(); ReturnValue = $"数据导入成功,共导入{CountRow - 1}条数据。"; } if (!flag) { ReturnValue = "数据存在问题!" + ReturnValue; } } catch (Exception) { return "服务器异常"; } return ReturnValue; } } }
建一个Excel文件或者将下载的模板excel填好测试数据
打开接口文档,选择这个Excel文件,进行导入
搞定!希望可以帮助到你、^-^