我在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();
}
答案 0 :(得分:0)
尝试此代码
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();
答案 1 :(得分:0)
这有效
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();
}
答案 2 :(得分:0)
尝试刷新并关闭 HttpResponse 请求。
response.OutputStream.Flush();
response.OutputStream.Close();
response.Flush();
response.Close();