Magicodes.IE.AspNetCore之一行代码多格式导出

主要步骤


1.安装包

Install-Package Magicodes.IE.AspNetCore


2.开始配置

在Startup.cs的Configure()方法中,在UseRouting()中间件之后,注册如下中间件

public void Configure(IApplicationBuilder app)
{
    app.UseRouting();
    app.UseMagiCodesIE();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

上面这种以中间件形式可以为我们提供导出服务,那么我们再看一下另一种方式如下所示:

  public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllers(options=>options.Filters.Add(typeof(MagicodesFilter)));
            }

上面两种方式都可以为我们提供导出服务,我们只需要对我们的控制器进行配置我们的特性,在这边呢 特性主要做的是一个标识作用,标识他的一些相关的内容数据,同时标识他可以当成文件导出。

[HttpGet("excel")]
[Magicodes(Type = typeof(ExportTestDataWithAttrs))]
public List<ExportTestDataWithAttrs> Excel()
{
    return GenFu.GenFu.ListOf<ExportTestDataWithAttrs>(100);
}

上面代码片段中我们标识这个类允许被导出。同时我们需要通过Type指定我们被导出类的类型。

这样填写完后我们可以通过对该地址的调用,但是注意我们必须要添加请求头以标识被导出的文件类型。如果不添加请求头,那么此处将返回的还是json格式的数据。请求头名称为Magicodes-Type

       /// <summary>
        ///     XLSX
        /// </summary>
        internal const string XLSXHttpContentMediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        /// <summary>
        ///     PDF
        /// </summary>
        internal const string PDFHttpContentMediaType = "application/pdf";
        /// <summary>
        ///     DOCX
        /// </summary>
        internal const string DOCXHttpContentMediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        /// <summary>
        ///     HTML
        /// </summary>
        internal const string HTMLHttpContentMediaType = "text/html";

如果说是模板导出word或者pdf甚至说html文件那么我们也是同样的操作如下所示:

[HttpGet("Word")]
        [Magicodes(Type = typeof(ReceiptInfo), TemplatePath = ".//ExportTemplates//receipt.cshtml")]
        public ReceiptInfo Word()
        {
            return new ReceiptInfo
            {
                Amount = 22939.43M,
                Grade = "2019秋",
                IdNo = "43062619890622xxxx",
                Name = "张三",
                Payee = "湖南心莱信息科技有限公司",
                PaymentMethod = "微信支付",
                Profession = "运动训练",
                Remark = "学费",
                TradeStatus = "已完成",
                TradeTime = DateTime.Now,
                UppercaseAmount = "贰万贰仟玖佰叁拾玖圆肆角叁分",
                Code = "19071800001"
            };
        }

我们还是需要对其指定Type,然后通过TemplatePath进行指定模板地址即可

同样的我们还可以通过请求头进行标识本次请求是否是文件格式导出。

       [HttpGet("pdf")]
        [Magicodes(Type = typeof(BatchPortraitReceiptInfoInput), TemplatePath = ".//ExportTemplates//batchReceipt.cshtml")]
        public BatchPortraitReceiptInfoInput Pdf()
        {


            var input = new BatchPortraitReceiptInfoInput
            {
                Payee = "湖南心莱信息科技有限公司",
                SealUrl =
                @"data:image/jpeg;base64....",
                LogoUrl =
                @"data:image/png;base64....",
                ReceiptInfoInputs = new List<BatchPortraitReceiptInfoDto>()
            };


            for (var i = 0; i < 500; i++)
                input.ReceiptInfoInputs.Add(new BatchPortraitReceiptInfoDto
                {
                    Amount = 22939.43M,
                    Grade = "2019秋",
                    IdNo = "43062619890622xxxx",
                    Name = "张三",
                    PaymentMethod = "微信支付",
                    Profession = "运动训练",
                    Remark = "学费",
                    TradeStatus = "已完成",
                    TradeTime = DateTime.Now,
                    UppercaseAmount = "贰万贰仟玖佰叁拾玖圆肆角叁分",
                    Code = "1907180000" + i
                });
            return input;
        }




        [HttpGet("Html")]
        [Magicodes(Type = typeof(ReceiptInfo), TemplatePath = ".//ExportTemplates//receipt.cshtml")]
        public ReceiptInfo Html()
        {
            return new ReceiptInfo
            {
                Amount = 22939.43M,
                Grade = "2019秋",
                IdNo = "43062619890622xxxx",
                Name = "张三",
                Payee = "湖南心莱信息科技有限公司",
                PaymentMethod = "微信支付",
                Profession = "运动训练",
                Remark = "学费",
                TradeStatus = "已完成",
                TradeTime = DateTime.Now,
                UppercaseAmount = "贰万贰仟玖佰叁拾玖圆肆角叁分",
                Code = "19071800001"
            };
        }


Swagger中使用


通过继承IOperationFilter接口,创建AddRequiredHeaderParameter类,添加一个header类型的参数,并且Header Name为Magicodes-Type如下所示:

 public class AddRequiredHeaderParameter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                operation.Parameters = new List<OpenApiParameter>();
            }


            operation.Parameters.Add(new OpenApiParameter
            {
                Name = "Magicodes-Type",
                In = ParameterLocation.Header,
                Required = false,
                Description = "根据HttpContentMediaType添加指定的header值,导出不同格式的文件。"
            });
        }
    }

然后转到ConfigureServices()方法中,在AddSwaggerGen方法中添加如下内容:

  c.OperationFilter<AddRequiredHeaderParameter>();


Reference

https://github.com/dotnetcore/Magicodes.IE

转载是一种动力 分享是一种美德

如果喜欢作者的文章,请关注【麦扣聊技术】订阅号以便第一时间获得最新内容。本文版权归作者和湖南心莱信息科技有限公司共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

文档官网:docs.xin-lai.com

原文作者:【HueiFeng】

QQ群:

编程交流群<85318032> 

产品交流群<897857351>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值