Magazine

ASP.NET: esportare il contenuto di una Gridview in un file leggibile da Excel

Creato il 21 aprile 2011 da Andreafortuna @AndyF
Snippet VB.NET (ma adattabile rapidamente anche in C#) rapido-rapido: salviamo il contenuto del controllo GridView1in un file html (leggibile quindi con MS Excel), mantenendone le formattazioni:
Dim SB As New StringBuilder()
Dim SW As New System.IO.StringWriter(SB)
Dim htmlTW As New HtmlTextWriter(SW)

Dim stringWrite As New System.IO.StringWriter()
Dim htmlWrite As New HtmlTextWriter(stringWrite)

Dim frm As New HtmlForm()
PlanningGridView.Parent.Controls.Add(frm)
frm.Attributes("runat") = "server"
frm.Controls.Add(<strong>GridView1</strong>)

frm.RenderControl(htmlWrite)
Response.ContentType = "application/csv"
Response.AddHeader("Content-Disposition", "attachment;filename=Export.xls;")
Response.Charset = ""
Response.Clear()
Response.Write(stringWrite.ToString())
Response.End()


Filed under: ASP.NET, featured, Programmazione

Ritornare alla prima pagina di Logo Paperblog