Search code examples
c#asp.netexcel-2007excel-2010export-to-excel

How to transmit a xlsx file as a aspx response output?


Goal: Transmit a .xlsx file from server to client using aspx response output.

Approach Tried: I used same response header for all of these approaches.

  1. Response.TransmitFile(fileName);
  2. Response.Output.Write(System.Text.Encoding.Default.GetString(File.ReadAllBytes(path))); //Tried with different encodings.
  3. Response.Output.Write(File.ReadAllText(path, System.Text.Encoding.Default)); //Tried with different encodings.

Result: Approach 1 worked (due to some infrastructure related constraints we cannot use this approach) . But approach 2 and 3 is not working. It's resulting a corrupted .xlsx file at client. Though .xlsx is collection of xml files and a binary format, I tried to open the file using notepad++ in both server and client. I noticed that they are little different.

Question:

  1. Why the file content is getting changed after it is transmitted to client?
  2. Is there any other way to send a xlsx file from server to client using aspx response output?

Solution

  • Please try the following:

    Response.ContentType = "application/vnd.ms-excel";
    Response.AppendHeader("Content-Disposition", "attachment; filename=myfile.xlsx");
    Response.BinaryWrite(File.ReadAllBytes(path));