2013-04-05 26 views
7

ho provato a trasferire i dati della vista griglia per eccellere .... ma l'output è un foglio excel vuoto. Come risolvere questo problema? Esiste un codice per trasferire il valore della vista griglia a excel foglio con base di dati?gridview data export to excel in asp.net

protected void btnexcel_Click1(object sender, EventArgs e) 
{ 
    Response.Clear(); 
    Response.Buffer = true; 
    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls"); 
    Response.Charset = ""; 
    Response.ContentType = "application/vnd.ms-excel"; 

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

    gvdetails.AllowPaging = false; 
    gvdetails.DataBind(); 
    gvdetails.HeaderRow.Style.Add("background-color", "#FFFFFF"); 
    gvdetails.HeaderRow.Cells[0].Style.Add("background-color", "green"); 
    gvdetails.HeaderRow.Cells[1].Style.Add("background-color", "green"); 
    gvdetails.HeaderRow.Cells[2].Style.Add("background-color", "green"); 
    for (int i = 0; i < gvdetails.Rows.Count;i++) 
    { 
     GridViewRow row = gvdetails.Rows[i]; 
     row.BackColor = System.Drawing.Color.White; 
     row.Attributes.Add("class", "textmode"); 
     if (i % 2 != 0) 
     { 
      row.Cells[0].Style.Add("background-color", "#C2D69B"); 
      row.Cells[1].Style.Add("background-color", "#C2D69B"); 
      row.Cells[2].Style.Add("background-color", "#C2D69B"); 
     } 
    } 

    string style = @"<style> .textmode { mso-number-format:\@; } </style>"; 
    Response.Write(style); 

    Response.Output.Write(sw.ToString()); 
    Response.End(); 
} 
+1

Qual è l'errore che state ottenendo qui? – Ratna

+1

@Ratna: il foglio Excel che sta generando è vuoto. Si prega di leggere il requisito correttamente. – pordi

+0

spero che tu sappia che questa non è un'esportazione excel, stai servendo una tabella html e un browser ingannevole con un tipo di contenuto sbagliato nella risposta. Ci sono numerosi problemi che puoi ottenere con questo approccio. http://stackoverflow.com/a/10245406/351383 –

risposta

12

Il foglio è vuoto perché il vostro scrittore stringa nel nulla. Ecco ciò che può aiutare a

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

    GridView1.RenderControl(htmlWrite); 

Ecco il codice completo

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

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


    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(); 

} 
+1

E se si tratta di una web part visiva e non c'è il controllo 'form' nella pagina? – SearchForKnowledge

-1

non mi ci v'è alcuna DataSource per l'gridview
Anche se si dispone di DataBind nel codice come

gvdetails.DataBind(); 
+0

Penso che DataBind sia lì, appena sotto AllowPaging – pordi

+0

Sto parlando di 'datasource'? –

+0

Sembra legittimo ... – pordi

0

Invece di fare tutte queste cose .. smussa si utilizza un approccio più semplice, come illustrato di seguito.

Response.ClearContent(); 
      Response.AddHeader("content-disposition", "attachment; filename=" + strFileName); 
      Response.ContentType = "application/excel"; 
      System.IO.StringWriter sw = new System.IO.StringWriter(); 
      HtmlTextWriter htw = new HtmlTextWriter(sw); 
      gv.RenderControl(htw); 
      Response.Write(sw.ToString()); 
      Response.End(); 

È possibile ottenere l'intera procedura dettagliata here

0

Un'altra cosa da controllare è assicurarsi che ViewState è acceso (ho appena risolto questo ieri). Se non hai viewstate attivo, il gridview sarà vuoto fino a quando non lo carichi di nuovo.

3

può essere un problema nell'associazione dati in esportazione excel. controlla che i dati siano correttamente inseriti in una griglia o meno.

Utilizzare questo codice per visualizzare la griglia di esportazione in foglio Excel e notare che è necessario aggiungere iTextSharp dll nel progetto.

protected void btnExportExcel_Click(object sender, EventArgs e) 
    { 
     Response.Clear(); 
     Response.Buffer = true; 
     Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls"); 
     Response.Charset = ""; 
     Response.ContentType = "application/vnd.ms-excel"; 

     StringWriter sw = new StringWriter(); 
     HtmlTextWriter hw = new HtmlTextWriter(sw); 
     GridView1.AllowPaging = false; 

     // Re-Bind data to GridView 

     using (CompMSEntities1 CompObj = new CompMSEntities1()) 
     { 
      Start = Convert.ToDateTime(txtStart.Text); 
      End = Convert.ToDateTime(txtEnd.Text); 

      GridViewSummaryReportCategory.DataSource = CompObj.SP_Category_Summary(Start, End); 
      SP_Category_Summary_Result obj1 = new SP_Category_Summary_Result(); 
      GridView1.DataBind(); 
      GridView1.Visible = true; 
      ExportTable.Visible = true; 
     } 

     //Change the Header Row back to white color 

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


     GridView1.Style.Add(" font-size", "10px"); 




     //Apply style to Individual Cells 

     GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green"); 
     GGridView1.HeaderRow.Cells[1].Style.Add("background-color", "green"); 
     GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green"); 
     GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green"); 
     GridView1.HeaderRow.Cells[4].Style.Add("background-color", "green"); 

     for (int i = 1; i < GridView1.Rows.Count; i++) 
     { 
      GridViewRow row = GridView1.Rows[i]; 

      //Change Color back to white 

      row.BackColor = System.Drawing.Color.White; 

      //Apply text style to each Row 

     // row.Attributes.Add("class", "textmode"); 

      //Apply style to Individual Cells of Alternating Row 

      if (i % 2 != 0) 
      { 
       row.Cells[0].Style.Add("background-color", "#C2D69B"); 
       row.Cells[1].Style.Add("background-color", "#C2D69B"); 
       row.Cells[2].Style.Add("background-color", "#C2D69B"); 
       row.Cells[3].Style.Add("background-color", "#C2D69B"); 
       row.Cells[4].Style.Add("background-color", "#C2D69B"); 
      } 
     } 
     GridView1.RenderControl(hw); 

     //style to format numbers to string 

     string style = @"<style> .textmode { mso-number-format:\@; } </style>"; 

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

penso che vi aiuterà a

string filename = String.Format("Results_{0}_{1}.xls", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString()); 
     if (!string.IsNullOrEmpty(GRIDVIEWNAME.Page.Title)) 
      filename = GRIDVIEWNAME.Page.Title + ".xls"; 

     HttpContext.Current.Response.Clear(); 

     HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename); 


     HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; 
     HttpContext.Current.Response.Charset = ""; 

     System.IO.StringWriter stringWriter = new System.IO.StringWriter(); 
     System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter); 



     System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm(); 
     GRIDVIEWNAME.Parent.Controls.Add(form); 
     form.Controls.Add(GRIDVIEWNAME); 
     form.RenderControl(htmlWriter); 

     HttpContext.Current.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"); 
     HttpContext.Current.Response.Write(stringWriter.ToString()); 
     HttpContext.Current.Response.End(); 
0

il modo migliore è quello di utilizzare ClosedXML. Di seguito è riportato il link di riferimento

https://closedxml.codeplex.com/wikipage?title=Adding%20DataTable%20as%20Worksheet&referringTitle=Documentation

ed è possibile utilizzare semplici

var wb = new ClosedXML.Excel.XLWorkbook(); 
DataTable dt = GeDataTable();//refer documentaion 

wb.Worksheets.Add(dt); 

Response.Clear(); 
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
Response.AddHeader("content-disposition", "attachment;filename=\"FileName.xlsx\""); 

using (var ms = new System.IO.MemoryStream()) { 
    wb.SaveAs(ms); 
    ms.WriteTo(Response.OutputStream); 
    ms.Close(); 
} 

Response.End();