Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How serve a downloadable excel file created with OpenXml, in .NET Core

enter image description hereI generated an excel file with OpenXml 2.7.2 in .NETCoreApp 1.1 and saved it into a project folder. Then in my function I read the bytes and try to return it as a File. I don't get an error, but in the response I just get back the binary. So it seems to work but doesn't get downloaded.

Here is my code:

[HttpGet]
[Route("export")]
public IActionResult Export()
    {
        return File(System.IO.File.ReadAllBytes(filePath),
        contentType: "application/octet-stream",
        fileDownloadName: "MySheet.xlsx");
        
    }

If anyone knows how to serve a downloadable excel file in .net core let me know. Any help is appreciated thanks!

UPDATE

I'm not sure the corruption is related to generating the excel file with OpenXml because even when I try to export an empty file that wasn't generated with OpenXml I get the same error message saying "The file is corrupt and cannot be opened". Its also not entirely related to Excel 2016 because I can open other excel files with it fine.

like image 833
jonv562 Avatar asked Aug 15 '17 21:08

jonv562


People also ask

How do I create an OpenXML file in Excel?

To create the basic document structure using the Open XML SDK, instantiate the Workbook class, assign it to the WorkbookPart property of the main document part, and then add instances of the WorksheetPart, Worksheet, and Sheet classes. This is shown in the sample code and generates the required SpreadsheetML markup.


1 Answers

I found a work around, so that I don't have to rely on reading the file and serving it which seems to be my issue. Now what I do is i generate the excel and return the url of the excel file. Then in the success response I call window.open().

this.export().subscribe(
        data => window.open(urlToExcelFile, "_blank"),
        err => console.log(err)  
    );
like image 59
jonv562 Avatar answered Sep 18 '22 00:09

jonv562