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>();
XMLHttpRequest使用
在XMLHttpRequest的使用中,和正常匯出來說幾乎一樣,不過需要額外注意以下幾個地方:
- 修改responseType為blob,
- 添加Http Header,
- 以及對二進制流的處理,
document.querySelector("#downloadexcel").onclick = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "https://localhost:5001/api/Magicodes/excel", true); //也可以使用Post
xmlhttp.responseType = 'blob';
xmlhttp.setRequestHeader("Magicodes-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
xmlhttp.send();
// readyState == 4 為請求完成,status == 200為請求成功回傳的狀態
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var name = xmlhttp.getResponseHeader("Content-disposition");
var filename = name.substring(20, name.length);
var blob = new Blob([xmlhttp.response], {
type: 'text/xlsx'
});
var Url = URL.createObjectURL(blob);
var link = document.createElement('a');
link.href = https://www.cnblogs.com/yyfh/archive/2021/04/22/Url;
link.download = filename;
link.click();
}
}
}
jQuery Ajax使用
對于jQuery Ajax和XMLHttpRequest的注意事項是一致的,詳細可參考如下代碼示例,不過目前對于示例的演示只是針對于Excel匯出的,關于其他格式的匯出,可參考我們前面介紹的Magicodes-Type常量內容,當然對于其他檔案的匯出同樣也是對responseType、以及blob型別進行修改,
$("#downloadexcel").click(function() {
$.ajax({
url: "https://localhost:5001/api/Magicodes/excel",
type: 'GET',
headers: {
'Magicodes-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
},
xhrFields: {
responseType: 'blob'
},
success: function(data, status, xhr) {
var name = xhr.getResponseHeader("Content-disposition");
var filename = name.substring(20, name.length);
var blob = new Blob([data], {
type: 'text/xlsx'
});
var Url = URL.createObjectURL(blob);
var link = document.createElement('a');
link.href = https://www.cnblogs.com/yyfh/archive/2021/04/22/Url;
link.download = filename;
link.click();
}
});
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/279151.html
標籤:.NET技术
