Saturday, August 12, 2006

Export Local Reports to Excel/PDF with one click

Local report are great but without an export function so this is one of my approaches to solve this issue.

ReportName : you give the name of the report and its reference path
ReportType : is an enum that is define after the subroutine (Excel/PDF)
DS : is the data set that contain all the information to link with the data
DSName: is the name of the data set so the binding will work

Private Sub ExportReport(ByVal ReportName As String, ByVal ReportType As ReportExportTypes, ByVal DS As DataSet, ByVal DSName As String)
'create report
Dim V As New ReportViewer
V.ProcessingMode = ProcessingMode.Local
V.LocalReport.ReportPath = Server.MapPath(ReportName)
For Each t As DataTable In DS.Tables
V.LocalReport.DataSources.Add(New ReportDataSource(DSName + "_" + t.TableName, t))
Next
' export report
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim bytes As Byte()
bytes = V.LocalReport.Render(ReportType.ToString, Nothing, mimeType, encoding, extension, streamids, warnings)
'start exporting
Response.ClearContent()
Response.ClearHeaders()
Response.Buffer = True
Select Case ReportType
Case ReportExportTypes.Excel
Response.ContentType = "application/vnd.ms-excel"
Case ReportExportTypes.PDF
Response.ContentType = "application/pdf"
End Select
Dim oStream As New IO.MemoryStream(bytes)
Response.BinaryWrite(oStream.ToArray())
Response.Flush()
Response.Close()
Response.End()
'cleaning up
oStream.Dispose()
V.Dispose()
End Sub


Public Enum ReportExportTypes
PDF
Excel
End Enum

No comments:

Post a Comment