I have a web api that converts datatable to excel bytes and sends it as a File. When I try to open the excel file, I get "We found a problem with some content in 'Test.xlsx'. Do you want us to try to recover as mush as we can? If you trust the source of this workbook, click yes.". When I click yes, I get "The file is corrupt and cannot be opened".
I have tried solutions mentioned in the following stack overflow questions:
ASP.NET MVC FileResult is corrupting files
Excel file (.xlsx) created by saving byte stream in C# cannot be opened
issue with returning HttpResponseMessage as excel file in WebAPI
'The file is corrupt and cannot be opened' OpenXML
[HttpPost]
public FileResult GetExcelFile(string parameters)
{
byte[] contents = generateContents(parameters);
// Method 1:
//Response.Clear();
// Response.ContentType = "application/octet-stream";
// Response.AddHeader("Content-Disposition", "attachment; filename=" + "Test.xlsx");
// Response.AddHeader("Content-Length", contents.Length.ToString());
// Response.BinaryWrite(contents);
// Response.Flush();
// Response.Close();
// Response.End();
return File(contents, "application/octet-stream", "Test.xlsx");
}
$.ajax({
url: webMethod,
type: "POST",
data: jQuery.param(parameters),
success: function (result, status, xhr) {
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, '');
}
}
var blob = new Blob([result]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
}
});
Thanks in advance for your help!
UPDATE:
The file returned from controller is 4 KB size and on the ajax side, the received blob size is 7 KB.