4

I have a List<T>, which I convert to a Datatable and then export that Datatable to Excel via Kingsoft-Spreadsheets using ClosedXML library.

However, for some reason the code is not working and the sheet is not getting downloaded. I am getting strange symbolic screen on my MVC view. I have attached the image for reference. Any help much appreciated.

enter image description here

Raidri
  • 17,258
  • 9
  • 62
  • 65
user3289773
  • 77
  • 1
  • 2
  • 11

3 Answers3

1

It looks like the Excel file is created correctly but your browser tries to open it like a plain text file. Set the content type and the content disposition header for the response correctly like this:

Response.AddHeader("content-disposition", "attachment; filename=" + myName);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // or "application/vnd.ms-excel"

For a full working code example see this question and its answers.

Community
  • 1
  • 1
Raidri
  • 17,258
  • 9
  • 62
  • 65
  • Sir,I added the contentType and AddHeader values as above already, despite that the error persists. – user3289773 Feb 09 '16 at 13:05
  • DataTable dtq = GetDT(List); MemoryStream MyMemoryStream = new MemoryStream(); using (XLWorkbook wb = new XLWorkbook()) { wb.Worksheets.Add(dtq); Response.Clear(); Response.Charset = ""; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment;filename=HelloWorld.xlsx"); Response.Buffer = true; wb.SaveAs(MyMemoryStream); MyMemoryStream.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); } – user3289773 Feb 09 '16 at 13:25
  • I tried different code snippets;yet no success,all the content is rendering to browser,any suggestions are welcomed – user3289773 Feb 15 '16 at 14:27
1

My bad, I was using ajax post back on Export Excel button click,there was no page postback.Acutally full page post back is required. I just added window.location.href with respective controller and action method and voila..its working fine.

user3289773
  • 77
  • 1
  • 2
  • 11
-1

You should avoid to call ajax :

function ExportSPReport() {
    window.location = '@Url.Action("ExportSPReport", "Report")';
    @*$.ajax({
            url: '@Url.Action("ExportSPReport", "Report")',
            type: "GET",
            success: function (data) {
                //alert(data);
                //$("#downloadFile").attr("href", data);
                //document.getElementById('downloadFile').click();
            },
            error: function (reponse) {
            }
        });
    }*@
}
Benjamin Lucidarme
  • 1,648
  • 1
  • 23
  • 39