0

I'm currently trying to generate and download an Excel file with ASP.NET MVC 4.

The file generation works fine, but the download have a behavior that I don't understand.

When I click on my download button:

@Html.ActionLink("DOWNLOAD", "Download", "Session", new { sessionId = Model.Session.Id, clientId = Model.Client.Id }, new { @class = "my-link" })

The excel file open with the right content, but it is saved at D:\data\documents\System.IO.MemoryStream which is not my default download directory.

And a empty file is saved at D:\downloads\infos.xls, which is my default download directory.

Directory D:\downloads

18/07/2016  05:10    <DIR>          .
18/07/2016  05:10    <DIR>          ..
18/07/2016  05:10                 0 infos.xls
           1 file(s)                0 octets


Directory D:\data\documents

18/07/2016  05:10    <DIR>          .
18/07/2016  05:10    <DIR>          ..
18/07/2016  05:10             8 521 System.IO.MemoryStream
           1 file(s)                8 521 octets

Here is my controller method:

using Excel = Microsoft.Office.Interop.Excel;

[Authorize]
public class SessionController : ControllerBase
{
    [HttpGet]
    public ActionResult Download(int sessionId, int clientId)
    {
        /* [...] Retreive infos */
        
        Excel.Application excelApp = new Excel.Application();
        Excel.Workbook workbook = excelApp.Workbooks.Add(System.Reflection.Missing.Value);
        Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];
    
        /* [...]  Insert infos in worksheet */

        byte[] data;

        using (var stream = new System.IO.MemoryStream())
        {
            workbook.SaveAs(stream);
            stream.Position = 0;
            data = stream.ToArray();
        }

        return File(data, "application/vnd.ms-excel", "infos.xls");
    }
}

Why are there are two downloaded files?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Blitz
  • 500
  • 3
  • 10

1 Answers1

0

It is because that the function is misused. From MSDN:

Worksheet.SaveAs Method (Excel)

Saves changes to the chart or worksheet in a different file.

The input requires a file name, but you put in a stream object.

workbook.SaveAs(stream);

That is why the strange file is created in your default user folder.

To understand why the empty file is created, check this code:

return File(data, "application/vnd.ms-excel", "infos.xls");

Here an empty stream is returned (the stream data is never set), with the name of infos.xls

To perform a file download, you can check the answers here.

Community
  • 1
  • 1
Hoàng Long
  • 10,746
  • 20
  • 75
  • 124
  • 1
    Thanks you. I didn't noticed that the examples I saw used another libraries. I switched from Microsoft Interop to EPPlus and it works fine, now i can save the file in a MemoryStream. – Blitz Jul 18 '16 at 04:48