2012-05-02 31 views
5

Quiero guardar el archivo de Excel que exporta los datos de la vista de cuadrícula. He escrito código para exportar datos de gridview para sobresalir, pero no sé cómo guardar el archivo exportado.Exportar vista de cuadrícula para sobresalir y guardar el archivo de Excel en la carpeta

que sigue es mi código para exportar a Excel gridview:

Response.Clear(); 
Response.Buffer = true; 
Response.ContentType = "application/vnd.ms-excel"; 
Response.AddHeader("content-disposition", "attachment;filename=MyFiles.xls"); 
Response.Charset = ""; 
this.EnableViewState = false; 
System.IO.StringWriter sw = new System.IO.StringWriter(); 
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); 
gvFiles.RenderControl(htw); 
Response.Write(sw.ToString()); 
Response.End(); 
+5

Usted sabe que no está exportando un archivo excel pero una tabla html? Excel puede interpretarlo, de todos modos no es un archivo de Excel real. Eche un vistazo a [EPPLus] (http://epplus.codeplex.com/releases/view/42439). –

+0

Como Tim dice, use EPPlus, es una biblioteca que generará archivos .xlsx reales para usted y luego podrá descargarlos. Lo he usado para una aplicación de monitoreo de presupuesto y es brillante. – markp3rry

+0

¿qué es DataSource para su vista de cuadrícula? –

Respuesta

10

Usted puede hacer esto:

private void ExportGridView() 
{ 
    System.IO.StringWriter sw = new System.IO.StringWriter(); 
    System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); 

    // Render grid view control. 
    gvFiles.RenderControl(htw); 

    // Write the rendered content to a file. 
    string renderedGridView = sw.ToString(); 
    System.IO.File.WriteAllText(@"C:\Path\On\Server\ExportedFile.xlsx", renderedGridView); 
} 
+1

dándome el error El control 'gvFiles' de tipo 'GridView' debe colocarse dentro de una etiqueta de formulario con runat = server. :( – Neo

+1

tiene la American National Standard anulación public void VerifyRenderingInServerForm (control Control) {} – Neo

0

que estás preguntando cómo guardar el archivo exportado ... Su código pone el contenido prestados del gridview (HTML) en la respuesta. En este caso, su navegador (del lado del cliente) recibirá esta respuesta y abrirá un cuadro de diálogo preguntándole dónde guardarlo. Por lo tanto, su navegador guardará el archivo por usted.

Si desea guardarlo desde el lado del servidor, no debe colocar la vista de cuadrícula renderizada en la respuesta. Escríbalo en un archivo en el disco duro local (como se muestra en la respuesta anterior).

Recuerde que, en un entorno que no sea su propia máquina de desarrollo (es decir, un entorno de producción), el proceso de trabajo ASP.NET puede no tener suficientes derechos de acceso para escribir en la ubicación especificada en el disco duro. Aquí hay un par de respuestas que adresses ese problema:

ASP.net user account permissions
ASP.NET + Access to the path is denied
System.UnauthorizedAccessException: Access to the path is denied

1

esto puede ayudarle a //

protected void exporttoexcel_Click(object sender, EventArgs e) 
{ 
    Response.Clear(); 

    Response.AddHeader("content-disposition", "attachment;filename=" attachment" + ".xls"); 

    Response.Charset = ""; 

    // If you want the option to open the Excel file without saving than 

    // comment out the line below 

    // Response.Cache.SetCacheability(HttpCacheability.NoCache); 

    Response.ContentType = "application/vnd.xls"; 

    System.IO.StringWriter stringWrite = new System.IO.StringWriter(); 

    System.Web.UI.HtmlTextWriter htmlWrite = 
    new HtmlTextWriter(stringWrite); 

    GridView1.RenderControl(htmlWrite); 

    Response.Write(stringWrite.ToString()); 

    Response.End(); 

} 
public override void VerifyRenderingInServerForm(Control control) 
{ 

    // Confirms that an HtmlForm control is rendered for the 
    //specified ASP.NET server control at run time. 

} 
+0

esto me ayudó a trabajar en el código completo de exportación-A-Excel. am simplemente no tan seguro de mantener 'VerifyRenderingInServerForm (control Control) 'vacío, sin embargo. – AceMark

1
public partial class exportgridtoexcel : System.Web.UI.Page 
{ 
    SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString.ToString()); 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!Page.IsPostBack) 
     { 
      GetData(); 
     } 
    } 
    public void GetData() 
    { 
     SqlDataAdapter sda = new SqlDataAdapter("select * from EmpData", con); 
     DataTable dt = new DataTable(); 
     sda.Fill(dt); 
     GridView1.DataSource = dt; 
     GridView1.DataBind(); 
    } 

    protected void btnDownload_Click(object sender, EventArgs e) 
    { 
     GetData(); 
     exporttoexcel("Report.xls", GridView1); 
     GridView1 = null; 
     GridView1.Dispose(); 



    } 
    public void exporttoexcel(string filename,GridView gv) 
    { 
     Response.ClearContent(); 
     Response.AddHeader("content-disposition", "attachment;filename=" + filename); 
     Response.ContentType = "applicatio/excel"; 
     StringWriter sw = new StringWriter(); ; 
     HtmlTextWriter htm=new HtmlTextWriter(sw); 
     gv.RenderControl(htm); 
     Response.Write(sw.ToString()); 
     Response.End(); 
    } 
    public override void VerifyRenderingInServerForm(Control control) 
    { 

    } 
} 

}

-1

primero agregar EPPLUS referirse conectar la biblioteca a la aplicación y agregarla usando OfficeOpenXml;

// objeto de negocio de clase

bocls clase {

string name; 

    public string NAME 
    { 
     get { return name; } 
     set { name = value; } 
    } 
    string id; 

    public string ID 
    { 
     get { return id; } 
     set { id = value; } 
    } 



    public bocls() { } 
    public bocls(string name, string id) 
    { 
     this.name = name; 
     this.id = id;   

    } 

// en caso de exportación, pulse el botón

protegida (object sender, EventArgs e) { vacío lbtnExport_Click

  List<bocls> list6 = new List<bocls>(); 
      //copy the grid view values into list 
      list6 = (from row in dataGridView1.Rows.Cast<DataGridViewRow>() 
      from cell in row.Cells.Cast<DataGridViewCell>() 
      select new 
      { 
       //project into your new class from the row and cell vars. 
      }).ToList(); 
    } 
      ExcelPackage excel = new ExcelPackage(); 
      var workSheet = excel.Workbook.Worksheets.Add("Products"); 
      var totalCols = GridView1.Rows[0].Cells.Count; 
      var totalRows = GridView1.Rows.Count; 
      var headerRow = GridView1.HeaderRow; 
      for (var i = 1; i <= totalCols; i++) 
      { 
       workSheet.Cells[1, i].Value = headerRow.Cells[i - 1].Text; 
      } 
      for (var j = 1; j <= totalRows; j++) 
      { 
       for (var i = 1; i <= totalCols; i++) 
       { 
        var item = list6.ElementAt(j - 1); 

        workSheet.Column(1).Width = 13; 
        workSheet.Column(2).Width = 10; 

        workSheet.Cells[j + 1, i].Style.WrapText = true; 

        if (headerRow.Cells[i - 1].Text == "ID") 
         workSheet.Cells[j + 1, i].Value = item.GetType().GetProperty("id").GetValue(item, null); 
        else if (headerRow.Cells[i - 1].Text == "NAME") 
         workSheet.Cells[j + 1, i].Value = item.GetType().GetProperty("name").GetValue(item, null); 

        workSheet.Cells[j + 1, i].Value = workSheet.Cells[j + 1, i].Value.ToString().Replace("<br/>", ""); 
       } 
      } 
      using (var memoryStream = new MemoryStream()) 
      { 

       Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
       string filename = Guid.NewGuid().ToString() + ".xlsx"; 
       Response.AddHeader("content-disposition", "attachment; filename=" + filename); 
       excel.SaveAs(memoryStream); 
       //add your destination folder 
       FileStream fileStream = new FileStream(@"C:\Users\karthi\Downloads\New folder\" + filename, FileMode.Create,FileAccess.Write,FileShare.Write); 
       memoryStream.WriteTo(fileStream); 
       fileStream.Close(); 
       memoryStream.WriteTo(Response.OutputStream); 
       memoryStream.Close(); 
       memoryStream.WriteTo(Response.OutputStream); 
       Response.Flush(); 
       Response.End(); 
      } 

    } 
Cuestiones relacionadas