我正在尝试从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;
}
这是我的AJAX通话
$(document).ready(function () {
$("#btnSubmit").click(function () {
window.location = "https://localhost:44318/custom/GetPlacementExcel/6/77";
})
})
但是我得到的答复是:
{“版本”:{“主要”:1,“次要”:1,“构建”:-1,“修订”:-1,“主要修订”:-1,“次要修订”:-1}, “ content”:{“ headers”:[{“ key”:“ Content-Disposition”,“ value”:[“ attachment; filename = Report.xlsx”]},{“ key”:“ Content-Type”,“ value“:[” application / octet-stream“]}]},” statusCode“:200,” reasonPhrase“:” OK“,” headers“:[],” requestMessage“:null,” isSuccessStatusCode“:true} < / p>
答案 0 :(得分:1)
Asp.Net Core不再使用HttpResponseMessage
,因此您需要使用适当的操作结果来返回所需的数据。
由于您已经将数据存储在流中,因此返回具有适当地雷类型和文件名的FileStreamResult
应该适合您的需求。
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
}