8

我正在尝试使用发送 xlsx 文件

Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/vnd-ms.excel";
Response.TransmitFile(file.FullName);
Response.End();

弹出IE对话框,我可以成功保存文件,然后从文件夹中打开它,效果很好。但是如果我在 IE 对话框中单击“打开”,我会得到“无法下载 myFile.xlsx”。我单击“重试”,它会打开 Excel,但会弹出“Excel 无法打开文件 'myFile.xlsx',因为文件格式或文件扩展名无效......”错误。
我目前正在以调试模式从 VS2010 运行该站点。

有谁知道为什么它会让我保存,但不能直接打开?

编辑
Chrome 只是下载它。FF尝试打开它,但给出了错误The file you are trying to open, 'myFile.xlsx.xls', is in a different format than specified by the file extension...我可以选择打开它并且它成功打开,但在只读模式下。
所以,这里正在发生一些时髦的事情。
文件名 = "我的文件.xlsx"

编辑 2
这是在 IE 9 中。我也尝试过octet-streamapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet作为 ContentType。

4

5 回答 5

5

这是因为您的 ContentType 错误。利用

Response.ContentType = "application/vnd.ms-excel";

编辑

如果它不起作用,你可以试试

FileStream sourceFile = new FileStream(file.FullName, FileMode.Open);
float FileSize;
FileSize = sourceFile.Length;
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)sourceFile.Length);
sourceFile.Close();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Length", getContent.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(getContent);
Response.Flush();
Response.End();
于 2012-03-20T15:53:03.007 回答
2

我曾经遇到过同样的问题,并通过修改应用程序服务器(在本例中为 IIS)发送的缓存指令来解决。有时您会在应用程序级别添加标头,以防止文件在某些​​情况下被保存,例如在 HTTPS 连接中。确保你没有提出相互矛盾的指令。

于 2012-08-28T20:29:58.810 回答
1

我遇到了类似的问题。

原来我是从流的末尾读取的,所以字节数组没有填满任何东西。

在读取流 (sourceFile.Read(getContent, 0, (int)sourceFile.Length);) 之前将流位置设置为 0 (sourceFile.Position=0;) 为我修复了它。

看看是否有帮助。

至于“Response.ContentType”,“application/vnd.ms-excel”对我有用。

FileStream sourceFile = new FileStream(file.FullName, FileMode.Open);
float FileSize;
FileSize = sourceFile.Length;
byte[] getContent = new byte[(int)FileSize];

源文件.位置=0;

sourceFile.Read(getContent, 0, (int)sourceFile.Length);
sourceFile.Close();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Length", getContent.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(getContent);
Response.Flush();
Response.End();
于 2012-08-15T06:38:41.560 回答
0

我被这个问题难住了,特别是对于较长的文件。

在我们的案例中,使用 Content-Length 标头解决了这个问题。一旦内容超过一定长度,您就会遇到此问题。

示例(其中 tempsbldr 是 StringBuilder):

  Response.AddHeader("Content-Length",tempsbldr.Length.ToString());
于 2015-01-05T03:26:43.997 回答
0

巧合的是,我正处于类似事件的中间......

用于 xlsx 的 MIME 类型是application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,请参阅此问题

于 2012-03-20T16:03:52.093 回答