.net core webapi 导出excel 功能

.net core webapi 导出excel 功能

1.nuget安装 EPPlus.Core
2.创建ExcelHelper类:

using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace StoveApi.Model
{
    public class ExcelHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataList">数据</param>
        /// <param name="headers">表头</param>
        /// <returns></returns>
        public static string CreateExcelFromList<T>(List<T> dataList, List<string> headers)
        {
            string sWebRootFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempExcel");
            if (!Directory.Exists(sWebRootFolder))
            {
                Directory.CreateDirectory(sWebRootFolder);
            }
            string sFileName = $@"tempExcel_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
            var path = Path.Combine(sWebRootFolder, sFileName);
            FileInfo file = new FileInfo(path);
            if (file.Exists)
            {
                file.Delete();
                file = new FileInfo(path);
            }
            using (ExcelPackage package = new ExcelPackage(file))
            {
                //创建sheet
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("sheet1");
                worksheet.Cells.LoadFromCollection(dataList, true);
                //表头字段
                for (int i = 0; i < headers.Count; i++)
                {
                    worksheet.Cells[1, i + 1].Value = headers[i];
                }
                package.Save();
            }
            return path;
        }
    }
}

3.创建ExportExcelController:
1).get方式:

[Route("ExportExcel")]
[HttpGet]
public IActionResult ExportExcel(){
    var personList=new List<Person>(){
        new Person(){id=1,name="wufan",age=25},
        new Person(){id=2,name="you",age=26}
    }
    var heads=new List<string>() { "编号", "姓名", "年龄"};
    var excelFilePath = ExcelHelper.CreateExcelFromList(personList,heads)
    return File(
        new FileStream(excelFilePath, FileMode.Open),
        "application/octet-stream",
        "ExcelNameHere.xlsx"
    );
}

2).post方式:

[Route("ExportExcel")]
[HttpPost]
public IActionResult ExportExcel(List<Person> personList){
    var heads=new List<string>() { "编号", "姓名", "年龄"};
    var excelFilePath = ExcelHelper.CreateExcelFromList(personList,heads)

    return File(
        new FileStream(excelFilePath, FileMode.Open),
        "application/octet-stream",
        "ExcelNameHere.xlsx"
    );
}

4.vue axios调用:

this.$axios({
        method: 'post', //或者get
        responseType: 'blob',
        url: this.url.exportExcel,
        data: this.formData
      }).then(function (res) {
        if (!res) return
        let blob = new Blob([res.data], {type: 'application/vnd.ms-excel;charset=utf-8'})
        let url = window.URL.createObjectURL(blob);
        let aLink = document.createElement("a");
        aLink.style.display = "none";
        aLink.href = url;
        aLink.setAttribute("download", "excel.xlsx");
        document.body.appendChild(aLink);
        aLink.click();
        document.body.removeChild(aLink); 
        window.URL.revokeObjectURL(url); 
      });
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值