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



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:


[sourcecode language="vb"]

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

[/sourcecode]

Published: April 21 2011

  • category: