AnswerBun.com

Exportar a Excel en ASP.NET

Stack Overflow en español Asked by CarlosR93 on December 21, 2020

Quisiera saber como exportar de Asp.net un DataGrid a Excel (si saben de alguna otra forma favor de explicarla), me sale un error, esta comentado en la linea donde aparece:

    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.ContentType = "application/ms-excel ";
        StringWriter sw = new StringWriter()
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
        GridView1.DataBind();
        GridView1.RenderControl(hw);;// <-- Aqui me sale el error:RegisterForEventValidation can only be called during Render();
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();

    }
      public override void VerifyRenderingInServerForm(Control control)
    {

    }

2 Answers

Si el control GridView no tiene controles AJAX como padre esto debería funcionar:

Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=ArchivoExportado.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";

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

GridView1.HeaderRow.Style.Add("background-color", "#F0F0F0");

foreach (TableCell tableCell in GridView1.HeaderRow.Cells)
{
    tableCell.Style["background-color"] = "#ffffff";
}

foreach (GridViewRow gridviewrow in GridView1.Rows)
{
    gridviewrow.BackColor = System.Drawing.Color.White;
    foreach (TableCell gridviewrowtablecell in gridviewrow.Cells)
    {
        gridviewrowtablecell.Style["background-color"] = "#ffffff";
    }
}

GridView1.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();

Si la grilla está dentro de controles AJAX:

  • Colocar el botón o enlace que realiza la exportación fuera del control UpdatePanel.
  • Agrega al UpdatePanel el trigger PostBackTrigger que apunte al botón que realiza la exportación.
  • Se debe llamar al método ScriptManager.RegisterPostBackControl() pasando como parámetro el botón de exportación.
  • De última, puedes hacer otra página .aspx que realice la exportación sin utilizar UpdatePanel.

Espero resulte útil.

Answered by Christian Amado on December 21, 2020

Este es un código para exportar un gridview muy similar que me funciona:

introducir la descripción de la imagen aquí

Este es el resultado: introducir la descripción de la imagen aquí

Así se implementa introducir la descripción de la imagen aquí

Código C#

introducir la descripción de la imagen aquí

 protected void ExportToExcel()
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            using (StringWriter sw = new StringWriter())
            {
                HtmlTextWriter hw = new HtmlTextWriter(sw);

                GridView1.AllowPaging = true;

                GridView1.HeaderRow.BackColor = Color.White;
                foreach (TableCell cell in GridView1.HeaderRow.Cells)
                {
                    cell.BackColor = GridView1.HeaderStyle.BackColor;
                }
                foreach (GridViewRow row in GridView1.Rows)
                {
                    row.BackColor = Color.White;
                    foreach (TableCell cell in row.Cells)
                    {
                        if (row.RowIndex % 2 == 0)
                        {
                            cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
                        }
                        else
                        {
                            cell.BackColor = GridView1.RowStyle.BackColor;
                        }
                        cell.CssClass = "textmode";
                    }
                }

                GridView1.RenderControl(hw);

                //style to format numbers to string
                string style = @"<style> .textmode { } </style>";
                Response.Write(style);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();
            }
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }

Answered by user22970 on December 21, 2020

Add your own answers!

Related Questions

Pregunta sobre el siguiente algoritmo de Dijkstra en Python

0  Asked on February 3, 2021 by estudiante

 

tengo el siguiente problema con este codigo

0  Asked on February 2, 2021 by israel-hidalgo

 

PHP OOP Clase multiple de search mysql

0  Asked on February 2, 2021 by nebulacrypt

   

No redireccionar al Home , al registrar usuario en laravel

1  Asked on February 2, 2021 by felipe-andres-larraguibel-aray

   

abrir dos ventanas modal

1  Asked on February 2, 2021 by asas

   

Convertir Query con select dentro de Select

1  Asked on February 2, 2021 by roberto-canela

     

ld returned 1 exit status Error

3  Asked on February 1, 2021 by juan-fernando-taipe-meza

 

¿Por qué no se aplica minmax() correctamente?

1  Asked on February 1, 2021 by david-paucar

   

Conectar base de datos con php

2  Asked on February 1, 2021 by hernanjs

   

Cómo borro un login banner?

0  Asked on February 1, 2021 by deimos-ff

 

Ask a Question

Get help from others!

© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP