如何将xlsx文件作为aspx响应输出进行传输

本文关键字:输出 响应 传输 aspx xlsx 文件 | 更新日期: 2023-09-27 18:20:19

目标:使用aspx响应输出将.xlsx文件从服务器传输到客户端。

尝试的方法:我对所有这些方法都使用了相同的响应头。

  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.

结果:方法1奏效了(由于一些与基础设施相关的限制,我们无法使用此方法)。但方法2和3不起作用。这导致客户端的.xlsx文件损坏。虽然.xlsx是xml文件和二进制格式的集合,但我尝试在服务器和客户端中使用notepad++打开该文件。我注意到他们有点不同。

问题:

  1. 为什么文件内容在传输到客户端后会发生更改
  2. 有没有其他方法可以使用aspx响应输出将xlsx文件从服务器发送到客户端

如何将xlsx文件作为aspx响应输出进行传输

请尝试以下操作:

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