0

I am using below code to create excel and download it in MVC

public ActionResult DownloadExcel()
        {
            ExcelPackage excel = new ExcelPackage();
            var workSheet = excel.Workbook.Worksheets.Add("Sheet1");

            //data binding to excel here


            var stream = new MemoryStream();
            excel.SaveAs(stream);

            string fileName = "SampleDemoExcel.xlsx";
            string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            stream.Position = 0;
            return File(stream, contentType, fileName);

        }

But above code not working for download.

I am able to save excel in local D: drive using below code

  excel.SaveAs(new FileInfo(@"D:\SampleDemoExcel.xlsx"));

But Instead of saving directly in some drive internally, I want download behavior.

How to achieve above scenario

Edit:

Actually, I am calling above method using $.ajax as below

$("#btnDownload").click(function(){
        debugger
        $.ajax({
            url: "/Home/DownloadExcel",
            headers: {
                'AntiForgeryToken': ''
            },
            type: "POST",          
            success: function (data) {
                debugger

            },
            error: function (x, h, r, thrownError) {
                //getting errors here as below
                //     h:parserror
                //  thrownerror:Error:Invalid XML �M�H�� . . .

               }
        });

    });

I am getting an error in ajax call as parsererror and Invalid XML �M�H�� ..

How to handle this

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Chandra sekhar
  • 356
  • 2
  • 12
  • `But above code not working for download.` How specifically is it not working? – mjwills Dec 14 '18 at 07:16
  • It's working, in fact there are several duplicate questions. What was the actual problem? Did you get an exception? The browser complained? The file was empty or corrupt? Something else? – Panagiotis Kanavos Dec 14 '18 at 09:34
  • Actually download behaviour is not working. Even I didn't get any error. – Chandra sekhar Dec 14 '18 at 09:55
  • An Ajax call is completely different from `download a file`. It's the Ajax call that fails because it expects an XML string. `xlsx` is a zip package containing XML files. You need to use `fetch` to retrieve the file and then `response.blob()` to get the actual data. After that, you need to decide what to do - you can't just save the file locally. The linked duplicate questions show what you need to do to save the file – Panagiotis Kanavos Dec 14 '18 at 15:33
  • @PanagiotisKanavos, Thanks a lot for your suggestion. It worked as expected. – Chandra sekhar Dec 17 '18 at 12:22

0 Answers0