How to generate excel batch files in MVC?

1

I need to generate separate Excel files. I tried doing a foreach

foreach (var item in listExtracts)
        {
            DataTable table = Mytable;
            var grid = new GridView { DataSource = table };

            grid.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=ArquivoExcelPessoas.xls");
            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();
        }

But the following error appears ...

I have tried other methods, at all in the first it generates the file, but in the loop it gives the error.

Am I doing something wrong or is there another way I can do this?

    
asked by anonymous 05.05.2016 / 13:57

1 answer

1

Look, each request can only return one response / respose . So the only way to return what you need, would be to create all the Excel files in memory with a MemoryStream , and then compress all into a zip files. So, you return this zip file with all the Excel spreadsheets you need.

This will even reduce traffic, since OpenXml documents have a high compression ratio.

    
05.05.2016 / 14:32