基于ABP和Magicodes实现Excel导出操作

2022-08-05

  前端使用的vue-element-admin框架,后端使用ABP框架,Excel导出使用的Magicodes.IE.Excel.Abp库。Excel导入和导出操作几乎一样,不再介绍。文本主要介绍Excel导出操作和过程中遇到的坑,主要是Excel文件导出后无法打开的问题。

一.Magicodes.IE库

1.Magicodes.IE库介绍

  Magicodes.IE是一个导入导出的通用库,它支持Dto导入导出、模板导出、花式导出以及动态导出,支持Excel、Csv、Word、Pdf和Html。总之,基本的和高级的导入和导出操作都是可以满足的。主要特点如下:

2.Magicodes.IE库的NuGet包

Magicodes.IE库相关的NuGet包如下所示:
(1)Magicodes.IE.Core,v2.6.4
(2)Magicodes.IE.Excel,v2.6.4
(3)Magicodes.IE.Excel.NPOI,v2.6.4
(4)Magicodes.IE.Excel.AspNetCore,v2.6.4
(5)Magicodes.IE.Pdf,v2.6.4
(6)Magicodes.IE.Word,v2.6.4
(7)Magicodes.IE.Html,v2.6.4
(8)Magicodes.IE.Csv,v2.6.4
(9)Magicodes.IE.AspNetCore,v2.6.4
(10)Magicodes.IE.EPPlus,v2.6.4
(11)Magicodes.IE.Excel.Abp,v2.6.4
(12)Magicodes.IE.Csv.Abp,v2.6.4
(13)Magicodes.IE.Html.Abp,v2.6.4
(14)Magicodes.IE.Pdf.Abp,v2.6.4
(15)Magicodes.IE.Word.Abp,v2.6.4

3.Magicodes.IE库的教程

(1)基础教程之导入学生数据[1]
(2)基础教程之导出Excel[2]
(3)基础教程之导出Pdf收据[3]
(4)在Docker中使用[4]
(5)动态导出[5]
(6)多Sheet导入[6]
(7)Csv导入导出[7]
(8)Excel图片导入导出[8]
(9)Excel模板导出之导出教材订购表[9]
(10)进阶篇之导入导出筛选器[10]
(11)Magicodes.IE之花式导出[11]
(12)Magicodes.IE.AspNetCore之一行代码多格式导出[12]
(13)性能测试[13]
(14)Excel合并行导入[14]
(15)Excel模板导出之动态导出[15]
(16)Magicodes.IE.Excel.AspNetCore之快速导出Excel[16]

二.基于ABP的Excel导出操作

1.Business.Application.Contracts

在该项目中添加Magicodes.IE.Excel.Abp类库。并且BusinessApplicationContractsModule需要依赖MagicodesIEExcelModule模块:
(1)ExportActivityDto类

public class ExportActivityDto : EntityDto<Guid?>
{
    /// <summary>
    /// 姓名或微信昵称
    /// </summary>
    [Required]
    [ExporterHeader(DisplayName = "姓名或微信昵称")]
    public string Name { get; set; }

    /// <summary>
    /// 所在省市区
    /// </summary>
    [Required]
    [ExporterHeader(DisplayName = "所在省市区")]
    public string Address { get; set; }

    /// <summary>
    /// 手机号
    /// </summary>
    [Required]
    [ExporterHeader(DisplayName = "手机号")]
    public string Phone { get; set; }

    /// <summary>
    /// 年龄
    /// </summary>
    [Required]
    [ExporterHeader(DisplayName = "年龄")]
    public string Age { get; set; }

    /// <summary>
    /// 备注
    /// </summary>
    [ExporterHeader(DisplayName = "备注")]
    public string Remark { get; set; }
}

(2)IActivityAppService

public interface IActivityAppService : IApplicationService
{
    // 导出活动列表
    Task<ActionResult> ExportActivity();
}

2.Business.Application

(1)ActivityAppService
通过构造函数注入的方式,依赖注入IExcelExporter:

/// <summary>
/// 通过Excel导出活动报名信息
/// </summary>
/// <returns></returns>
public async Task<ActionResult> ExportActivity()
{
    var query = await _repository.GetQueryableAsync();
    var dto = ObjectMapper.Map<List<Activity>, List<ExportActivityDto>>(query.ToList());
    var result = await _excelExporter.ExportAsByteArray(dto);
    var fs  = new MemoryStream(result);

    return new XlsxFileResult(stream: fs, "活动报名信息表.xlsx");
}

(2)ActivityAutoMapperProfile

public class ActivityAutoMapperProfile : Profile
{
    public ActivityAutoMapperProfile()
    {
        CreateMap<Activity, ExportActivityDto>();
    }
}

3.Business.HttpApi

(1)ActivityController

[HttpGet]
[Route("export-activity")]
public Task<ActionResult> ExportActivity()
{
    return _ActivityAppService.ExportActivity();
}

4.Excel导出操作vue代码

导出按钮相关的vue代码如下:

<el-button class="filter-item" size="mini" type="success" icon="el-icon-download" @click="handleExport()">导出</el-button>

导出函数的vue代码如下:

handleExport() {
  var that = this;
  that.$axios.get('/api/app/activity/export-activity').then(res => {
    this.$notify({
      title: '成功',
      message: '导出成功',
      type: 'success',
      duration: 2000
    });
    var blob = new Blob([res], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });
    let url = window.URL.createObjectURL(blob); //创建下载的链接
    let a = document.createElement("a"); //生成一个a标签
    a.setAttribute("href", url);
    a.setAttribute("download", that.$activityExcelName);
    a.style.display = "none"; //将a标签隐藏
    document.body.appendChild(a); //将a标签添加到body中
    a.click(); //触发a标签的点击事件
    window.URL.revokeObjectURL(url); //释放掉blob对象
    a.remove() //将a标签从body中移除
  }).catch(() => {
    this.$message({
      type: 'info',
      message: '没有权限导出'
    });
  });
  }

其中that.$axios.get中的get()代码如下:

get(url) {
  return new Promise((resolve, reject) => {
    axios.get(url, { responseType: "blob" })
      .then(response => {
        resolve(response.data)
      }, err => {
        // Message({
        //   message: err.error.message,
        //   type: 'error',
        //   duration: 5 * 1000
        // })
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

说明:一定要特别注意加上responseType: "blob",否则就会报文件格式或者文件扩展名无效的错误。自己尝试了下,换成responseType: "arraybuffer"也是可以的。

三.MagicodesIEXXXModule模块源码

1.MagicodesIEExcelModule源码

 public class MagicodesIEExcelModule: AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        context.Services.AddScoped<IExcelExporter, ExcelExporter>();
        context.Services.AddScoped<IExcelImporter, ExcelImporter>();
        context.Services.AddScoped<IExportFileByTemplate, ExcelExporter>();
        //TODO:处理筛选器
    }
}

2.MagicodesIECsvModule源码

public class MagicodesIECsvModule: AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        context.Services.AddScoped<ICsvExporter, CsvExporter>();
        context.Services.AddScoped<ICsvImporter, CsvImporter>();
    }
}

3.MagicodesIEHtmlModule源码

public class MagicodesIEHtmlModule: AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        context.Services.AddScoped<IHtmlExporter, HtmlExporter>();
    }
}

4.MagicodesIEPdfModule源码

public class MagicodesIEPdfModule: AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        context.Services.AddScoped<IPdfExporter, PdfExporter>();
    }
}

5.MagicodesIEWordModule源码

public class MagicodesIEWordModule: AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        context.Services.AddScoped<IWordExporter, WordExporter>();
    }
}

参考文献:
[1]基础教程之导入学生数据:https://urlify.cn/neI7Vz
[2]基础教程之导出Excel:https://urlify.cn/yiei6f
[3]基础教程之导出Pdf收据:https://urlify.cn/7FjuA3
[4]在Docker中使用:https://github.com/dotnetcore/Magicodes.IE/blob/master/docs/4.在Docker中使用.md
[5]动态导出:https://github.com/dotnetcore/Magicodes.IE/blob/master/docs/5.动态导出.md
[6]多Sheet导入:https://github.com/dotnetcore/Magicodes.IE/blob/master/docs/6.多Sheet导入.md
[7]Csv导入导出:https://github.com/dotnetcore/Magicodes.IE/blob/master/docs/7.Csv导入导出.md
[8]Excel图片导入导出:https://urlify.cn/Ybyey2
[9]Excel模板导出之导出教材订购表:https://urlify.cn/vqyQnq
[10]进阶篇之导入导出筛选器:https://urlify.cn/Nzmmim
[11]Magicodes.IE之花式导出:https://urlify.cn/QRZRN3
[12]Magicodes.IE.AspNetCore之一行代码多格式导出:https://github.com/dotnetcore/Magicodes.IE/blob/master/docs/12.Magicodes.IE.AspNetCore之一行代码多格式导出.md
[13]性能测试:https://github.com/dotnetcore/Magicodes.IE/blob/master/docs/13.性能测试.md
[14]Excel合并行导入:https://github.com/dotnetcore/Magicodes.IE/blob/master/docs/Excel合并行导入.md
[15]Excel模板导出之动态导出:https://github.com/dotnetcore/Magicodes.IE/blob/master/docs/Excel模板导出之动态导出.md
[16]Magicodes.IE.Excel.AspNetCore之快速导出Excel:https://github.com/dotnetcore/Magicodes.IE/blob/master/docs/AspNetCore之快速导出Excel.md
[17]麦扣官方文档:https://docs.xin-lai.com/
[18]添加对Abp Vnext模块的封装和支持:https://github.com/dotnetcore/Magicodes.IE/issues/318
[19]abp框架Excel导出--基于vue:https://www.cnblogs.com/JerryMouseLi/p/13399027.html
[20]abp-vue导入导出excel:https://cloud.tencent.com/developer/article/1552255
[21]使用Magicodes.IE快速导出Excel:https://www.cnblogs.com/codelove/p/15117226.html
[22]dotnetcore/Magicodes.IE:https://github.com/dotnetcore/Magicodes.IE