当前位置: 首页 > article >正文

.NetCore WebAPI 导入、导出Excel文件

转自:转载地址

.NetCore WebAPI 导入、导出Excel文件

导入

思路:上传Excel文件,使用MemoryStream 在内存中加载,使用NPOI读取内容到Model类中。

/// <summary>
/// 导入Excel文件
/// </summary>
/// <param name="excelFile"></param>
/// <returns></returns>
[HttpPost]
public IActionResult UploadUserInfo(IFormFile excelFile)
{
    try
    {
        var postFile = Request.Form.Files[0];
        string extName = Path.GetExtension(postFile.FileName);
        if (!new string[] { ".xls", ".xlsx" }.Contains(extName))
        {
            return Ok(new
                      {
                          error = 1,
                          msg = "必须是Excel文件"
                      });
        }
    MemoryStream ms = new MemoryStream();
    postFile.CopyTo(ms);
    ms.Position = <span class="hljs-number">0</span>;
    IWorkbook wb = null;
    <span class="hljs-keyword">if</span> (extName.ToLower().Equals(<span class="hljs-string">".xls"</span>)) <span class="hljs-comment">// 97-2003版本</span>
    {
        wb = new HSSFWorkbook(ms);
    }
    <span class="hljs-keyword">else</span>
    {
        wb = new XSSFWorkbook(ms); <span class="hljs-comment">// 2007以上版本</span>
    }

    ISheet sheet = wb.GetSheetAt(<span class="hljs-number">0</span>);

    <span class="hljs-comment">//总行数(0开始)</span>
    <span class="hljs-type">int</span> totalRow = sheet.LastRowNum;
    <span class="hljs-comment">// 总列数(1开始)</span>
    <span class="hljs-type">int</span> totalColumn = sheet.GetRow(<span class="hljs-number">0</span>).LastCellNum;

    List&lt;Stu&gt; stuList = new();
    <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">1</span>; i &lt;= totalRow; i++)
    {

        IRow row = sheet.GetRow(i);
        <span class="hljs-comment">// 判定第5列的值是不是日期,日期的值类型可以按日期来读,也可以用数据的方式来读</span>
        var isDate = DateUtil.IsCellDateFormatted(row.GetCell(<span class="hljs-number">4</span>));                   

        <span class="hljs-built_in">string</span> StuName = row.GetCell(<span class="hljs-number">0</span>).StringCellValue;
        <span class="hljs-type">int</span> Sex = row.GetCell(<span class="hljs-number">1</span>).StringCellValue == <span class="hljs-string">"男"</span> ? <span class="hljs-number">0</span> : <span class="hljs-number">1</span>;
        <span class="hljs-built_in">string</span> Phone = ((<span class="hljs-type">long</span>)row.GetCell(<span class="hljs-number">2</span>).NumericCellValue).ToString();
        <span class="hljs-type">int</span> CId = (<span class="hljs-type">int</span>)row.GetCell(<span class="hljs-number">3</span>).NumericCellValue;
        DateTime InDate = row.GetCell(<span class="hljs-number">4</span>).DateCellValue;
        decimal JF = (decimal)row.GetCell(<span class="hljs-number">5</span>).NumericCellValue;

        <span class="hljs-comment">// 第6列有可能是空的</span>
        <span class="hljs-built_in">string</span> Pic = <span class="hljs-string">""</span>;
        <span class="hljs-keyword">if</span>(row.GetCell(<span class="hljs-number">6</span>) != null)
        {
            CellType type = row.GetCell(<span class="hljs-number">6</span>).CellType;
            <span class="hljs-keyword">if</span> (type != CellType.Blank)
            {
                Pic = row.GetCell(<span class="hljs-number">6</span>).StringCellValue;
            }
        }

        <span class="hljs-type">int</span> State = (<span class="hljs-type">int</span>)row.GetCell(<span class="hljs-number">7</span>).NumericCellValue;

        var stu = new Stu
        {
            StuName = StuName,
            Sex = Sex,
            Phone = Phone,
            CId = CId,
            InDate = InDate,
            JF = JF,
            Pic =Pic,
            State = State,
            IsOk = <span class="hljs-literal">true</span>,
        };
        stuList.Add(stu);
    }
    db.Stu.AddRange(stuList);
    db.SaveChanges();
    wb.Close();
    <span class="hljs-keyword">return</span> Ok(new
              {
                  error = <span class="hljs-number">0</span>,
                  importCount = stuList.Count,
                  msg = <span class="hljs-string">""</span>
              });
}
catch (Exception)
{
    throw;
}

}

导出

导出后端

思路:使用NPOI使用 IWorkBook ,一行一行写入要导出数据,最终返回 FileContentResult

默认(不使用模板)
/// <summary>
/// 导出所有的信息为Excel
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult ExportExcel()
{
    try
    {
        var list = db.Stu.Where(s => s.IsOk).ToList();
    IWorkbook wb = new XSSFWorkbook();
    ISheet sheet = wb.CreateSheet(<span class="hljs-string">"Sheet1"</span>);
    <span class="hljs-comment">// 第一行 标题</span>
    IRow row = sheet.CreateRow(<span class="hljs-number">0</span>);
    row.CreateCell(<span class="hljs-number">0</span>).SetCellValue(<span class="hljs-string">"姓名"</span>);
    row.CreateCell(<span class="hljs-number">1</span>).SetCellValue(<span class="hljs-string">"性别"</span>);
    row.CreateCell(<span class="hljs-number">2</span>).SetCellValue(<span class="hljs-string">"手机号码"</span>);
    row.CreateCell(<span class="hljs-number">3</span>).SetCellValue(<span class="hljs-string">"学院"</span>);
    row.CreateCell(<span class="hljs-number">4</span>).SetCellValue(<span class="hljs-string">"入学日期"</span>);
    row.CreateCell(<span class="hljs-number">5</span>).SetCellValue(<span class="hljs-string">"综合积分"</span>);
    row.CreateCell(<span class="hljs-number">6</span>).SetCellValue(<span class="hljs-string">"照片"</span>);
    row.CreateCell(<span class="hljs-number">7</span>).SetCellValue(<span class="hljs-string">"状态"</span>);
    <span class="hljs-comment">// 第二行 写数据</span>
    <span class="hljs-type">int</span> i = <span class="hljs-number">1</span>;
    foreach (var item in <span class="hljs-built_in">list</span>)
    {
        row = sheet.CreateRow(i);
        row.CreateCell(<span class="hljs-number">0</span>).SetCellValue(item.StuName);
        row.CreateCell(<span class="hljs-number">1</span>).SetCellValue(item.Sex == <span class="hljs-number">0</span> ? <span class="hljs-string">"男"</span> : <span class="hljs-string">"女"</span>);
        row.CreateCell(<span class="hljs-number">2</span>).SetCellValue(<span class="hljs-type">double</span>.Parse(item.Phone));
        row.CreateCell(<span class="hljs-number">3</span>).SetCellValue(item.CId);

        <span class="hljs-comment">// 日期格式的导出</span>
        ICell cell = row.CreateCell(<span class="hljs-number">4</span>);
        ICellStyle style = wb.CreateCellStyle();
        IDataFormat format = wb.CreateDataFormat();
        style.DataFormat = format.GetFormat(<span class="hljs-string">"yyyy-MM-dd"</span>);
        cell.CellStyle = style;
        cell.SetCellValue(DateTime.Parse(item.InDate.ToString(<span class="hljs-string">"yyyy-MM-dd"</span>)));

        row.CreateCell(<span class="hljs-number">5</span>).SetCellValue((<span class="hljs-type">double</span>)item.JF);
        row.CreateCell(<span class="hljs-number">6</span>).SetCellValue(item.Pic);
        row.CreateCell(<span class="hljs-number">7</span>).SetCellValue(item.State);
        i++;
    }
    <span class="hljs-comment">// 写 WorkBook信息到 内存流中</span>
    byte[] buffer = null;
    using (MemoryStream ms = new MemoryStream())
    {
        wb.Write(ms);
        buffer = ms.ToArray();
    }
     <span class="hljs-comment">// .xlsx文件对应的Mime信息</span>
     var mime = new FileExtensionContentTypeProvider().Mappings[<span class="hljs-string">".xlsx"</span>];
    <span class="hljs-keyword">return</span> File(buffer, mime, <span class="hljs-string">"学生信息.xlsx"</span>);

}
catch (Exception)
{
    throw;
}

}

使用模板
/// <summary>
/// 导出Excel(使用模板)
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult ExportExcelByTemplate()
{
    try
    {
        IWorkbook wb = null;
        var template = Directory.GetCurrentDirectory() + @"\wwwroot\Template\template.xlsx";
        // 按模板内容创建 IWorkbook
        using(FileStream fs = new FileStream(template, FileMode.OpenOrCreate))
        {
            wb = new XSSFWorkbook(fs);
        }
    var <span class="hljs-built_in">list</span> = db.Stu.Where(s =&gt; s.IsOk).ToList();

    ISheet sheet = wb.GetSheetAt(<span class="hljs-number">0</span>);
    <span class="hljs-type">int</span> i = <span class="hljs-number">1</span>;
    IRow row = null;
    foreach (var item in <span class="hljs-built_in">list</span>)
    {
        row = sheet.CreateRow(i);
        row.CreateCell(<span class="hljs-number">0</span>).SetCellValue(item.StuName);
        row.CreateCell(<span class="hljs-number">1</span>).SetCellValue(item.Sex == <span class="hljs-number">0</span> ? <span class="hljs-string">"男"</span> : <span class="hljs-string">"女"</span>);
        row.CreateCell(<span class="hljs-number">2</span>).SetCellValue(<span class="hljs-type">double</span>.Parse(item.Phone));
        row.CreateCell(<span class="hljs-number">3</span>).SetCellValue(item.CId);

        <span class="hljs-comment">// 日期格式的导出</span>
        ICell cell = row.CreateCell(<span class="hljs-number">4</span>);
        ICellStyle style = wb.CreateCellStyle();
        IDataFormat format = wb.CreateDataFormat();
        style.DataFormat = format.GetFormat(<span class="hljs-string">"yyyy-MM-dd"</span>);
        cell.CellStyle = style;
        cell.SetCellValue(DateTime.Parse(item.InDate.ToString(<span class="hljs-string">"yyyy-MM-dd"</span>)));

        row.CreateCell(<span class="hljs-number">5</span>).SetCellValue((<span class="hljs-type">double</span>)item.JF);
        row.CreateCell(<span class="hljs-number">6</span>).SetCellValue(item.Pic);
        row.CreateCell(<span class="hljs-number">7</span>).SetCellValue(item.State);
        i++;
    }

    byte[] buffer = null;
    using (MemoryStream ms = new MemoryStream())
    {
        wb.Write(ms);
        buffer = ms.ToArray();
    }
     <span class="hljs-comment">// .xlsx文件对应的Mime信息</span>
     var mime = new FileExtensionContentTypeProvider().Mappings[<span class="hljs-string">".xlsx"</span>];
    <span class="hljs-keyword">return</span> File(buffer, mime, <span class="hljs-string">"学生信息.xlsx"</span>);

}
catch (Exception)
{
    throw;
}

}

导出前端(调用)

使用 axios 调用

// 导出为Excel文件(.xlsx)
// 简单方法
    exportExce() {
      let url =
        "http://localhost:23474/api/Stu/ExportExcel?page=1&size=4&bId=0"; //可以在路径中传递参数
      window.location.href = url;
    },
// 标准方法
exportExcel() {
    this.axios
        .get("http://localhost:23474/api/Stu/ExportExcel", {
        responseType: "blob",
    })
        .then((res) => {
        var blob = new Blob([res.data], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        var a = document.createElement("a"); // js创建一个a标签
        var href = window.URL.createObjectURL(blob); // 文档流转化成Base64
        a.href = href;
        a.download = "学生数据.xlsx"; // 下载后文件名
        document.body.appendChild(a);
        a.click(); // 点击下载
        document.body.removeChild(a); // 下载完成移除元素
        window.URL.revokeObjectURL(href);
    });
},

http://www.kler.cn/a/457393.html

相关文章:

  • openEuler ARM使用vdbench50407
  • 时间复杂度与空间复杂度计算方法介绍
  • 【数据结构】(Python)差分数组。差分数组与树状数组结合
  • GoldenDB组件及对应的用户和进程
  • 前端安全措施:接口签名、RSA加密、反调试、反反调试、CAPTCHA验证
  • Vue 针对浏览器参数过长实现浏览器参数加密解密
  • html+css+js网页设计 美食 家美食1个页面
  • Day32 # 和 ## 运算符
  • 云计算学习架构篇之HTTP协议、Nginx常用模块与Nginx服务实战
  • 探索 Java 权限修饰符的奥秘
  • C#中相等比较 == 和 Equal函数 对比
  • 在Ubuntu下通过Docker部署Cloudflared Tunnel服务器
  • SpringBoot整合springmvc
  • 遗传算法——附python实现与各方法的作用与修改
  • 【强化学习】深度确定性策略梯度算法(DDPG)详解(附代码)
  • 碰一碰发视频矩阵系统源码搭建,支持OEM
  • Qt仿音乐播放器:QFileDialog添加本地文件
  • BMS存储模块的设计
  • idea 禁用/关闭 sonarlint 后台自动分析(默认开启可能会引起idea卡顿)
  • 【K8s】专题十五(6):Kubernetes 网络之 Pod 网络调试
  • Netty 2024 常见面试题
  • 个人用途虚拟机VM 17安装Ubuntu 16.04.5 图解
  • 大数据面试笔试宝典之Spark面试
  • Java网约车项目实战:实现抢单功能详解
  • golangb并发,Sync包中Mutes,WaitGroup, NewCond的适应
  • 八大排序——直接插入排序