首页 > 解决方案 > 下载 .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();
}

标签: c#excel

解决方案


这有效

      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();
    }

推荐阅读