.Net Core 使用NPOI導入數據

一、搭建環境

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框架,操作數據庫更便捷)

 

 

 

 話不多說,貼代碼:

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文件,進行導入

 

 

 搞定!希望可以幫助到你、^-^

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章