Search code examples
c#asp.netexport-to-excelepplus

EPPlus: How do I have 2 ExcelPackage.SaveAs?


I am using EPPlus for my export to Excel function. I need to have 2 SaveAs, 1st SaveAs which is a save dialogue to allow user Open/Save/SaveAs and my 2nd SaveAs to allow the Excel file to be saved directly into the specified folder in the server as a backup copy.

Thus my issue here is that my 2nd SaveAs does not work (no error popup during debug, no files generated either for 2nd SaveAs).

Please advice. Thanks!

ExcelPackage package = new ExcelPackage();
.....
code for loading data table
.....
var filename = @"REPORT_" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xlsx";

The below codes works (my 1st SaveAs for user to choose to Open/Save/SaveAs):

Response.Clear();
package.SaveAs(Response.OutputStream);
Response.AddHeader("content-disposition", "attachment; filename=" + filename + ";");
Response.Charset = "";
Response.ContentType = "application/vnd.xlsx";
Response.End();

The below code does not work (my 2nd SaveAs to save file directly into server):

string path = @"C:\Users\testacc\Desktop\Test\" + filename +";";
Stream stream = File.Create(path);
package.SaveAs(stream);
stream.Close();
byte[] data = File.ReadAllBytes(path);

Solution

  • Why not look at it and achieve the other way, in the reverse order. First save the generated file on the server and then transmit the saved file to the client.

    1. Create the package

      ExcelPackage package = new ExcelPackage();
      .....
      code for loading data table
      .....
      var filename = @"REPORT_" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xlsx";
      
    2. Save to the server

      string path = @"C:\Users\testacc\Desktop\Test\" + filename +";";
      Stream stream = File.Create(path);
      package.SaveAs(stream);
      stream.Close();
      
    3. Transmit saved file to the client

      try {
          response.Clear();
          response.ContentType = "application/vnd.xlsx";
          response.AddHeader("content-disposition", "attachment; filename=" + filename + ";");
          response.TransmitFile(path);
          response.Flush();
      } catch (Exception ex) {
          // any error handling mechanism
      } finally {
          HttpContext.Current.ApplicationInstance.CompleteRequest();
      }