Search code examples
c#.netexport-to-excel

excel file is being downloaded on the server not on the client


I have a button on my web app to export an Excel file but when the user clicks the button, my mistake is that I am downloading the document on the server, not on the client. This is my code:

var excelApp = new Excel.Application();
String f = excelApp.GetSaveAsFilename(nameOfDocument, "Excel Filter (*.xlsx), *.xlsx").ToString();
workSheet.SaveAs(f);

I am using Office Interop Excel.

Could you help me please?


Solution

  • First, you shouldn't use Interop on your asp.net server. Microsoft discourages that since it can lead to undesired behavior.

    Second, you should save the document, and output it to the response stream. One way to do that is using TransmitFile:

    // save your file to a temporary location
    string pathToTheSavedFile = ...;
    
    // then transmit the file
    HttpContext.Current.Response.TransmitFile(pathToTheSavedFile);