Convert a Crystal Report to Excel


In this article we learn about how to Convert a Crystal Report to Excel with the code snippet .

This Code show how to convert a Crystal Report to Excel Document.



'First Create a crystal Report.
' Drag and drop the Crystal Report Viewer in the form
' copy this code on top of the code
Imports System.Data
Imports System.Data.SqlClient
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared

Private myDS As New Dataset1() ' Dataset you created.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim rpt As New CrystalReport1() 'The report you created.
Dim myConnection As SqlConnection
Dim MyCommand As New SqlCommand()
Dim myDA As New SqlDataAdapter()

Try

myConnection = New SqlConnection("Data Source=localhost;Integrated Security=SSPI;" & _
"Initial Catalog=pubs;")
MyCommand.Connection = myConnection
MyCommand.CommandText = "SELECT * FROM authors"
MyCommand.CommandType = CommandType.Text
myDA.SelectCommand = MyCommand

myDA.Fill(myDS, "authors")
rpt.SetDataSource(myDS)
CrystalReportViewer1.ReportSource = rpt

Catch Excep As Exception
MessageBox.Show(Excep.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'this is the code which converts crystalreport to Excel document
Dim reportExcel As New CrystalReport1() ' Report Name
Dim strExportFile As String = "d:\Test.xls"
reportExcel.ExportOptions.ExportDestinationType = ExportDestinationType.DiskFile
reportExcel.ExportOptions.ExportFormatType = ExportFormatType.Excel
Dim objOptions As DiskFileDestinationOptions = New DiskFileDestinationOptions()
objOptions.DiskFileName = strExportFile
reportExcel.ExportOptions.DestinationOptions = objOptions
reportExcel.SetDataSource(myDS)
reportExcel.Export()
objOptions = Nothing
reportExcel = Nothing

End Sub





Comments

No responses found. Be the first to comment...