【发布时间】:2019-01-06 21:09:25
【问题描述】:
我正在尝试从 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";
})
})
但我得到的回应是:
{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-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}
【问题讨论】:
标签: asp.net-core asp.net-core-2.0 asp.net-core-webapi