Free Information Technology Magazines and eBooks

Saturday, May 23, 2009

ASP.NET: How to export crystal report to PDF, Excel or Word using C#

Most of system end-users, prefer their report in PDF, Excel or Word format over Crystal Report. The reason is they have more control over the report specially if they need to modify the report and add more information. This is where export facility comes handy. For todays article, you will learn How to export crystal report to PDF, Excel or MS Word document.


First we need to include the following namespaces on your Using directives.

using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports;


Next is to setup the database connection using TableLogOnInfo class.

TableLogOnInfo LogInfo = new TableLogOnInfo();
LogInfo.ConnectionInfo.ServerName = "mnlho8ap33";
LogInfo.ConnectionInfo.UserID = "sa";
LogInfo.ConnectionInfo.Password = "12345678";
LogInfo.ConnectionInfo.DatabaseName = "Access";



Then connect to the database and load the report.

CrystalDecisions.CrystalReports.Engine.ReportDocument O_Report = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
//Load the report
O_Report.Load(Server.MapPath(Request.QueryString["file"].ToString()));
O_Report.Database.Tables[0].ApplyLogOnInfo(LogInfo);


After loading the report, pass the parameters required.

//pass the parameters
ParameterDiscreteValue discreteVal = new ParameterDiscreteValue();
discreteVal.Value = Request.QueryString["parameter1"].ToString();
O_Report.SetParameterValue("parameter1", discreteVal);


Then finally, export the crystal report using ExportToHttpResponse method.

string exportfilename = "DMR" + Request.QueryString["parameter1"].ToString();
switch (cboFormat.Text.ToLower())
{
case "microsoft word":
O_Report.ExportToHttpResponse(ExportFormatType.WordForWindows, Response, true, exportfilename);
break;
case "microsoft excel":

O_Report.ExportToHttpResponse(ExportFormatType.Excel, Response, true, exportfilename);
break;
default:
O_Report.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, exportfilename);
break;
}


You can also download the Export to PDF/Excel/Word VB 2005 sample project.


For more ASP.NET coding tips, subscribe now

0 comments: