ASP.NET MVC returning an xls file inside an zip file

空扰寡人 提交于 2020-01-07 07:50:29

问题


I have an asp.net mvc action that returns an xls file:

public void Excel(string filename)
{
    DAOSolicitacao dao = new DAOSolicitacao();

    System.Threading.Thread.Sleep(5000);
    var products = dao.GetSolicitacoes(); 

    var grid = new GridView();
    grid.DataSource = products;
    grid.DataBind();

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", filename));
    Response.ContentType = "application/ms-excel";
    Response.Charset = "";

    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
}

How can I make this xls file return into an zip file ?


回答1:


Google! Is your friend!

DotNetZip Library




回答2:


There is already a build in class ZipFile

http://msdn.microsoft.com/en-us/library/system.io.compression.zipfile.aspx

that you can try

using (ZipFile zipFile = new ZipFile())
{
    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", string.Format("attachment; filename={0}",   filename));
    Response.ContentType = "application/ms-excel";
    Response.Charset = "";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    grid.RenderControl(htw);
    zipFile.Save(Response.Output.Write(sw.ToString())); 
    return File(zipFile.GetBytes(), "application/zip", downloadFileName);

}


来源:https://stackoverflow.com/questions/17281105/asp-net-mvc-returning-an-xls-file-inside-an-zip-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!