I am trying to dynamically generate an excel version of an HTML report using .NET Aspose Cells.
The situation requires the generation of the Excel file and then the passing of the Excel file to the user's browser for download.
I create a csv file from with the data I need from the HTML report.
Then I open an Excel template I created using Aspose Cells and populate it with the CSV contents.
This works fine when I save the file locally to my machine but never when I try to pass it back to the Javascript to download it via the browser.
Please find below my code:
C# - Aspose Excel Workbook Generation
Workbook temp = new Workbook(System.Web.Hosting.HostingEnvironment.MapPath($"~/templates/") + @"excel_template.xlsx");
Worksheet ws = temp.Worksheets[0];
ws.Cells.ImportCSV(csvFile, ",", false, 1, 0);
// Used to test the excel populates correctly
temp.Save("Path_to_file" + fileName + ".xlsx", SaveFormat.Xlsx);
Then I try to pass that Workbook to the browser via a HttpResponseMessage.
After a lot of searching, this is what I came up with (NOTE: could be completely wrong)
MemoryStream ms = new MemoryStream();
temp.Save(ms, SaveFormat.Xlsx);
byte[] bytes = ms.ToArray();
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(bytes);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName + ".xlsx";
response.Content.Headers.ContentType = new MediaTypeHeaderValue("Application/x-msexcel");
return response;
Then I try to interact with the response using Javascript to generate a download of the excel file that is visible via the browser.
JavaScript Code
$.get(ROOT + 'api_route', { 'csv': csv }, function (data) {
var byteArray = new Uint8Array(data);
var link = document.createElement('a');
var blob = new Blob(byteArray, { type: "application/octet-stream" });
link.href = window.URL.createObjectURL(blob);
link.download = "sample_excel_" + new Date(Date.now()).toLocaleDateString() + '_' + new Date(Date.now()).toLocaleTimeString() + ".xlsx";
link.click();
});
This downloads the excel file via the browser but the file is corrupted and it can't be opened.
What I am asking is, can this actually be done first off?
If so, is there something obvious that I have done wrong?