The*_*ddy 2 asp.net-core asp.net-core-webapi asp.net-core-2.0
我正在尝试从 Web API 返回 excel 文件,但我收到的是 JSON 响应,而不是下载的文件。
using (var excel = new ExcelPackage())
{
var sheet = excel.Workbook.Worksheets.Add("Placments");
var taxonomyConnStr = GetConnectionString(DatabaseSettings.ConnectionStringNames.Taxonomy);
var plookConnStr = GetConnectionString(DatabaseSettings.ConnectionStringNames.Plook);
var content = _repo.GetPlacementDataTable(masterAgencyDivisionId, masterClientId, plookConnStr);
if (content.Rows.Count > 0)
{
Color colFromHex = System.Drawing.ColorTranslator.FromHtml("#000000");
sheet.Row(1).Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
sheet.Row(1).Style.Fill.BackgroundColor.SetColor(colFromHex);
sheet.Row(1).Style.Font.Color.SetColor(Color.White);
sheet.Row(1).Style.Font.Bold = true;
sheet.Row(1).Style.Font.Size = 12;
sheet.Cells[1, 1].LoadFromDataTable(content, true);
sheet.Cells[sheet.Dimension.Address].AutoFitColumns();
}
else
{
sheet.Cells[1, 1].LoadFromText("There is no data for filtered results. Please adjust your selections.");
}
var stream = new MemoryStream();
excel.SaveAs(stream);
stream.Position = 0;
var result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-sream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Report.xlsx"
};
return result;
}
Run Code Online (Sandbox Code Playgroud)
这是我的 AJAX 调用
$(document).ready(function () {
$("#btnSubmit").click(function () {
window.location = "https://localhost:44318/custom/GetPlacementExcel/6/77";
})
})
Run Code Online (Sandbox Code Playgroud)
但我得到的回应是:
{“版本”:{“主要”:1,“次要”:1,“构建”:-1,“修订版”:-1,“主要修订版”:-1,“次要修订版”:-1},“内容” :{"headers":[{"key":"Content-Disposition","value":["attachment; filename=Report.xlsx"]},{"key":"Content-Type","value": [“application/octet-stream”]}]},“statusCode”:200,“reasonPhrase”:“确定”,“headers”:[],“requestMessage”:null,“isSuccessStatusCode”:true}
Asp.Net Core 不再使用HttpResponseMessage,因此您需要使用适当的操作结果来返回所需的数据。
由于您已经将数据存储在流中,因此返回FileStreamResult具有正确的矿井类型和文件名的 a 应该适合您的需求。
public IActionResult MyAction() {
//...code removed for brevity
var stream = new MemoryStream();
excel.SaveAs(stream);
stream.Position = 0;
var fileName = "Report.xlsx";
var mimeType = "application/vnd.ms-excel";
//return the data stream as a file
return File(stream, mimeType, fileName); //<-- returns a FileStreamResult
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5261 次 |
| 最近记录: |