ClosedXML / ClosedXML.Extensions.WebApi

MIT License
34 stars 16 forks source link

ClosedXML Extensions WebAPI does not work with ASP .NET Core Web API #1

Open augustoproiete opened 5 years ago

augustoproiete commented 5 years ago

Following up from @Pankraty's comment on ClosedXML/#1283... Looking at the different ClosedXML extensions, it seems ClosedXML.Extensions.AspNet would be the most appropriate extension for ASP .NET Core Web API projects, so the below is just for awareness.


Instead of the file being downloaded, we receive a text response:

image

Sample project that reproduces the above:


NuGet packages added to the project:

<PackageReference Include="ClosedXML" Version="0.94.2" />
<PackageReference Include="ClosedXML.Extensions.WebApi" Version="0.2.1" />

Example code from the README:

    [ApiController]
    public class ExcelController : ControllerBase
    {
        [HttpGet]
        [Route("api/file/{id}")]
        public async Task<HttpResponseMessage> DownloadFile(int id)
        {
            var wb = await BuildExcelFile(id);
            return wb.Deliver("excelfile.xlsx");
        }

        private async Task<XLWorkbook> BuildExcelFile(int id)
        {
            var t = Task.Run(() =>
            {
                var wb = new XLWorkbook();
                var ws = wb.AddWorksheet("Sheet1");
                ws.FirstCell().SetValue(id);

                return wb;
            });

            return await t;
        }
    }
silverio27 commented 4 years ago

Opa! Alguém conseguiu resolver esse problema. Também só obtive a resposta em json. Mas implementei de outra forma: ` [HttpGet] [Route("{id}")] public async Task DownloadFile(int id) { var wb = await BuildExcelFile(id); var workbookBytes = new byte[0]; using (var ms = new MemoryStream()) { wb.SaveAs(ms); workbookBytes = ms.ToArray(); } return File(workbookBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Teste.xlsx" ); }

    private async Task<XLWorkbook> BuildExcelFile(int id)
    {
        //Creating the workbook
        var t = Task.Run(() =>
        {
            var wb = new XLWorkbook();
            var ws = wb.AddWorksheet("Sheet1");
            ws.FirstCell().SetValue(id);

            return wb;
        });

        return await t;
    }`