Web API 2-Excel电子表格(文件已损坏,无法打开)

问题描述 投票:0回答:1

[我正在尝试使用Web API下载一个简单的xlsx文件,但该文件始终损坏,我仍未弄清楚原因。我正在使用C#ClosedXML.Excel,并遵循一个基本示例,可在此处找到:

ClosedXml examples

[HttpGet]
[Route("campaigns/{id}/contact-points/excel")]
[SwaggerResponse(491, "TokenInvalid")]
[SwaggerResponse(HttpStatusCode.NotFound)]
[SwaggerResponse(HttpStatusCode.Forbidden)]
[ResponseType(typeof(HttpResponseMessage))]
public async Task<IHttpActionResult> GetCampaignContactPointsExcel(int id, int frequency, string txtFrequency)
{
    var wb = new XLWorkbook();
    var ws1 = wb.Worksheets.Add("Sheet1");
    ws1.Cell("A1").SetValue(1).AddToNamed("value1");

    var ws2 = wb.Worksheets.Add("Sheet2");

    ws2.Cell("A1").SetFormulaA1("=value1").AddToNamed("value2");

    var responseMessage = new HttpResponseMessage(HttpStatusCode.OK);
    using (var memoryStream = new MemoryStream())
    {
            wb.SaveAs(memoryStream);
            responseMessage.Content = new ByteArrayContent(memoryStream.ToArray());
            responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            responseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "ContactPoints.xlsx"
                };
                memoryStream.Close();
            }
            return ResponseMessage(responseMessage);
    }

我也在使用摇摇欲坠,当我单击链接时,它会下载文件并将其作为xlsx文件打开,但始终表示它已损坏。

c# excel asp.net-web-api2 memorystream
1个回答
0
投票

后端代码中没有错。在前端,您需要设置responseType ='blob'

© www.soinside.com 2019 - 2024. All rights reserved.