1

I'm using EPPlus to create an excel file on the server. The problem is that I wan't the file to be saved on the clients harddrive and when I the application up on a server I believe this will save the file on the server harddrive.

Is it possible to send this file back to the client/browser some how?

public void CreateAnnuityExcelSheet(List<Calculation> cList, FormCollection form, int DTCyear)
{
    List<Calculation> newList = new List<Calculation>();
    newList.Add(cList.First()); //Getting the values for the first row
    var StartValue = newList[0].StartValue;
    var radio = form["advanceOrArrears"];
    string fileName = newList[0].CalculationName;
    string path = @"C:\ExcelFiles\" + fileName + ".xlsx"; //Path for the file
    FileInfo info = new FileInfo(path);
    info.Directory.Create(); //If C:\ExcelFiles does not exist, create it
    if (!info.Exists)
    {
        using (ExcelPackage package = new ExcelPackage(info))
        {
            ExcelWorksheet ws = package.Workbook.Worksheets.Add(fileName);
            //Styles for the sheet
            package.Save();
        }
    }
}
Mo Patel
  • 2,321
  • 4
  • 22
  • 37
MrProgram
  • 5,044
  • 13
  • 58
  • 98

3 Answers3

2

The easiest way would be to send the bytes as File to browser. If your library for creating Excel files allows you to save to stream (like for example ClosedXML does) then you can do in your MVC action

var stream = new MemoryStream();
workbook.SaveAs(stream);
stream.Position = 0;

return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", "file.xlsx");

If you can't save it to memory stream then save it to server's disc and then you can just pass file path and content type to return File().

Episodex
  • 4,479
  • 3
  • 41
  • 58
  • I have tried this now and it won't work. When I runt the method nothing happens. And what I want is that the client get's the downloaded file – MrProgram Apr 24 '14 at 11:09
  • But you're running this action from a browser window, yes? By "nothing happens" you mean white screen in browser? – Episodex Apr 24 '14 at 12:38
0

I've used a httphandler for sending the byte file object to the browser.

This link should help, Generating a file, then launching a secure download

Community
  • 1
  • 1
DavidFletcher
  • 77
  • 1
  • 11
0

So save the file on the server then transmit it to the user in your controller:

return new FilePathResult(myFilePath, 
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
spender
  • 117,338
  • 33
  • 229
  • 351