NetCoreAPI操作Excel表格

一、开源框架MiniExcel

MiniExcel(推荐使用)

MiniExcel简单、高效避免OOM的.NET处理Excel查、写、填充数据工具。

目前主流框架(EPPlus ,NPIO)大多需要将数据全载入到内存方便操作,但这会导致内存消耗问题,MiniExcel 尝试以 Stream 角度写底层算法逻辑,能让原本1000多MB占用降低到几MB,避免内存不够情况。

二、引入MiniExce的Nuget包

Install-Package MiniExcel -Version 1.26.5

三、操作Excel示例

1.准备两个Excel表格

在这里插入图片描述

两张数据格式

在这里插入图片描述

2.创建Student类

因为MiniExcel生成的是强类型数据,所以需要一个类来承接数据

using System.ComponentModel.DataAnnotations;

namespace _02_EFWithOptionExcel
{
    public class Student
    {
        public int ID { get; set; }
        [StringLength(50)]
        public string Name { get; set; }
        [StringLength(2)]
        public string Sex { get; set; }
        [StringLength(11)]
        public string Phone { get; set; }
        [StringLength(200)]
        public string Address { get; set; }
    }
}

3.使用EFCore来操作数据

创建Excel控制器

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace _02_EFWithOptionExcel.Controllers
{
   
    [Route("api/[controller]")]
    [ApiController]
    public class MinExcelController : ControllerBase
    {
        private readonly StudentDbContext _studentDbContext;
        private readonly IWebHostEnvironment _webHostingEnvironment;
        public MinExcelController(IWebHostEnvironment hostingEnvironment,StudentDbContext studentDbContext)
        {
            _webHostingEnvironment = hostingEnvironment;
            _studentDbContext = studentDbContext;
        }

        [HttpPost]
       public List<Student>  Get([FromForm] IFormCollection formCollection)
        {
            //文件集合
            FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
            //学生集合
            List<Student> lists = new List<Student>();
            //遍历集合中的文件
            foreach (IFormFile file in fileCollection)
            {
                //打开文件stream
                Stream stream = file.OpenReadStream();
                //操纵stream,生成集合
                var rows = stream.Query<Student>().ToList();
                //将两个excel合并为一个集合
                lists = lists.Union(rows).ToList();
            }
            //批量添加数据
            _studentDbContext.Student.AddRange(lists);
            //保存数据
            _studentDbContext.SaveChanges();

            return lists;
        }
    }
}

四、测试Api

在这里插入图片描述

posted @   有诗亦有远方  阅读(57)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示