Tuesday, June 22, 2010

Export GridView with Images to Word, Excel and PDF Formats

Export to Word Format

Private Sub Word_Export()

Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.doc")

Response.Charset = ""
Response.ContentType = "application/vnd.ms-word "

Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)

GridView1.AllowPaging = False
GridView1.DataBind()
GridView1.RenderControl(hw)

Response.Output.Write(sw.ToString())
Response.Flush()
Response.End()

End Sub



Export to Excel Format

Private Sub Excel_Export()

Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls")

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

Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)

GridView1.AllowPaging = False
GridView1.DataBind()

For i As Integer = 0 To GridView1.Rows.Count - 1
Dim row As GridViewRow = GridView1.Rows(i)
'Apply text style to each Row
row.Attributes.Add("class", "textmode")
Next

GridView1.RenderControl(hw)

'style to format numbers to string

Dim style As String = ""

Response.Write(style)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.End()

End Sub


Export to PDF Format

Private Sub PDF_Export()

Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition","attachment;filename=GridViewExport.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)

Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)

GridView1.AllowPaging = False
GridView1.DataBind()
GridView1.RenderControl(hw)

Dim sr As New StringReader(sw.ToString())
Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
Dim htmlparser As New HTMLWorker(pdfDoc)

PdfWriter.GetInstance(pdfDoc, Response.OutputStream)

pdfDoc.Open()
htmlparser.Parse(sr)
pdfDoc.Close()
Response.Write(pdfDoc)
Response.End()

End Sub

No comments:

Post a Comment