c# - 下载 .xlsx 文件返回损坏的文件
问题描述
我在 C# 中制作了以下按钮,当在界面中选择该按钮时,它返回一个损坏的 .xlsx 文件。原始文件本身没有任何问题。
protected void download_Data(object sender, EventArgs e)
{
string strFullPath = Server.MapPath("~/Content/Demo User data file.xlsx");
string strContents = null;
System.IO.StreamReader objReader = default(System.IO.StreamReader);
objReader = new System.IO.StreamReader(strFullPath);
strContents = objReader.ReadToEnd();
objReader.Close();
string attachment = "attachment; filename=Demo User data file.xlsx";
Response.ClearContent();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", attachment);
Response.Write(strContents);
Response.End();
}
解决方案
这有效
protected void Button1_Click(object sender, EventArgs e)
{
string strFullPath = Server.MapPath("~/Content/Sample Contact.xlsx");
string attachment = "attachment; filename=Sample_Contact.xlsx";
Response.ClearContent();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", attachment);
Response.BinaryWrite(File.ReadAllBytes(strFullPath));
Response.End();
}
推荐阅读
- ubuntu - 在 docker 容器内创建网络命名空间时出错。错误:mount --make-shared /run/netns failed: Permission denied
- php - 生成数百个随机唯一优惠券代码并插入数据库
- javascript - 如何在 HTML 中显示 JavaScript 文件中的代码
- google-data-studio - 如何在 DataStudio 的多个页面中标记/更改下一个按钮?
- libreoffice - 更改 libreoffice 的默认证书管理器
- java - 并行运行 testNG 套件
- python-3.x - 重新映射opencv拼接图像
- java - 在 TextView Android studio 上显示来自数据库的信息
- python - 为什么 python lxml etree xpath 返回多个元素?
- html - 使用 CSS 将元素放置在容器底部