Downloading .xlsx file returning corrupt file

2019-08-20 05:04发布

I have made the following button in C#, and it is returning a corrupt .xlsx file when the button is selected in the interface. The original file itself has no issues whatsoever.

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
2条回答
爷的心禁止访问
2楼-- · 2019-08-20 05:30

Try this code

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();
查看更多
小情绪 Triste *
3楼-- · 2019-08-20 05:36

This works

      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();
    }
查看更多
登录 后发表回答