Linked Questions

Popular Questions

I am trying to download a simple xlsx file using web api but the file is always corrupt and I am yet to figure out why.I am using C# ClosedXML.Excel and following a basic example which can be found here:

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);
    }

I am also using swagger and when I click on the link it downloads the file and opens it as a xlsx file but it always says it's corrupt.

Related Questions