How to Batch Generate Excel Files in MVC?

Asked

Viewed 101 times

1

I need to generate separate excel files. I tried to do in 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...

inserir a descrição da imagem aqui

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

Am I doing something wrong or is there another way to do it?

1 answer

1


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

This will even reduce traffic, since Openxml document have a high compression index.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.