C# 正在下载.xlsx文件,返回损坏的文件
我在C#中创建了以下按钮,当在界面中选择该按钮时,它将返回一个损坏的.xlsx文件。原始文件本身没有任何问题C# 正在下载.xlsx文件,返回损坏的文件,c#,excel,C#,Excel,我在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
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();
}
试试这个代码
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=myfile.xlsx");
Response.BinaryWrite(File.ReadAllBytes(Server.MapPath("~/Content/Demo User data file.xlsx")));
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();
}
尝试刷新并关闭HttpResponse请求
response.OutputStream.Flush();
response.OutputStream.Close();
response.Flush();
response.Close();
为什么不简单地调用映射的文件路径呢?double/application是一个错误。在将其调整为:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet之后,我仍然得到相同的损坏excel文件。您所说的调用响应.Writefile是什么意思?有什么问题吗?我替换了“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”;使用“application/vnd.ms excel”。这没有帮助..我必须为文件指定一些内容吗?您必须添加“using System.IO;”谢谢!!这很有帮助。