Bind Crystal Report In ASP.NET Application And Export In PDF And Excel Format

I have already created Crystal Report for this example. You can read my previous article for creating Crystal Report,
 
Step By Step Creating Grouping In Crystal Report

Now follow the below steps for calling Crystal Report from ASP.NET code.
 
Step 1:  Create a new ASP.NET project and add report in your project, here I have created Report folder and added 'CrystalReport2.rpt' file in it.
 
 
 
 
 
Step 2: Now add WebForm in your project by right click on Project, Add, then clicking Webform. Give it a name,
 
 
Step 3:  Now, let's design your page, Drag and Drop 'RadioButtonList' and add 2 Items 'PDF' and 'Excel' add button, give a name 'btnSubmit' .
  1. <div>  
  2.      
  3.     <asp:RadioButtonList ID="RadioButtonList1" runat="server">  
  4.         <asp:ListItem Selected="True">PDF</asp:ListItem>  
  5.         <asp:ListItem>Excel</asp:ListItem>  
  6.     </asp:RadioButtonList>  
  7.     <asp:Button ID="btnSubmit" runat="server"  Text="Submit" OnClick="btnSubmit_Click" />  
  8.      
  9. </div>  
Step 5: For Crystal Report you need 2 packages from NuGet Package manager: CrystalDecisions.Shared and CrystalDecisions.CrystalReports.Engine,
 
 
 
Step 6:  After that we have to add assemblies in our code.
  1. using CrystalDecisions.CrystalReports.Engine;  
  2. using CrystalDecisions.Shared;  
  3. using System.IO;  
  4. using System.Configuration;  
  
 
Step 7: For Connection String I have added Keys in Web.Config file, Add the following code in your web.config in <appSettings> tab.

Here I have created 4 keys for Server name, Database name, User Id, and Password. 
 
 
 
Step 8: On Button Click event, add the following code: 
  •    Create object for crystal report Export option class.
  •    Create object for destination option - for set path of your pdf/excel file save.
  •    Map your crystal report path.
  •    Set database Connection.
  •    Select report format (pdf/excel).  
  1. protected void btnSubmit_Click(object sender, EventArgs e)    
  2. {    
  3.        
  4.     //Create object for crystal report Export option class    
  5.     ExportOptions exopt = default(ExportOptions);    
  6.   
  7.     //create object for destination option - for set path of your pdf file save     
  8.     DiskFileDestinationOptions dfdopt = new DiskFileDestinationOptions();    
  9.   
  10.         
  11.     ReportDocument RptDoc = new ReportDocument();    
  12.   
  13.     //Map your crystal report path    
  14.     RptDoc.Load(Server.MapPath("~/Report/CrystalReport2.rpt"));    
  15.     //Set database Connection    
  16.     setDbInfo(RptDoc, ConfigurationManager.AppSettings["V_DSN"], ConfigurationManager.AppSettings["V_DB"], ConfigurationManager.AppSettings["V_DBUserID"], ConfigurationManager.AppSettings["V_DBPwd"]);    
  17.   
  18.     if (RadioButtonList1.SelectedItem.Text.ToString() == "PDF")    
  19.     {    
  20.     //Report pfd name    
  21.     string fname = "Report1.pdf";    
  22.         dfdopt.DiskFileName = Server.MapPath(fname);    
  23.   
  24.         exopt = RptDoc.ExportOptions;    
  25.         exopt.ExportDestinationType = ExportDestinationType.DiskFile;    
  26.   
  27.         //for PDF select PortableDocFormat for excel select ExportFormatType.Excel    
  28.         exopt.ExportFormatType = ExportFormatType.PortableDocFormat;    
  29.         exopt.DestinationOptions = dfdopt;    
  30.             
  31.     //finally export your report document    
  32.     RptDoc.Export();    
  33.   
  34.     //To open your PDF after save it from crystal report    
  35.   
  36.     string Path = Server.MapPath(fname);    
  37.   
  38.     FileInfo file = new FileInfo(Path);    
  39.   
  40.     Response.ClearContent();    
  41.   
  42.     Response.AddHeader("Content-Disposition""attachment; filename=" + file.Name);    
  43.     Response.AddHeader("Content-Length", file.Length.ToString());    
  44.     Response.ContentType = "application/pdf";    
  45.     Response.TransmitFile(file.FullName);    
  46.     Response.Flush();    
  47.   
  48.       
  49.     RptDoc.Dispose();    
  50.     RptDoc.Close();    
  51.     RptDoc = null;    
  52.     ////End    
  53.   
  54.        
  55.   
  56.     }    
  57.     else    
  58.     {    
  59.        // Excel Code goes here...    
  60.   
  61.         string fname = "Report1.xls";    
  62.         dfdopt.DiskFileName = Server.MapPath(fname);    
  63.   
  64.         exopt = RptDoc.ExportOptions;    
  65.         exopt.ExportDestinationType = ExportDestinationType.DiskFile;    
  66.   
  67.         exopt.ExportFormatType = ExportFormatType.Excel;    
  68.         exopt.DestinationOptions = dfdopt;    
  69.            
  70.         RptDoc.Export();    
  71.            
  72.         string Path = Server.MapPath(fname);    
  73.   
  74.         FileInfo file = new FileInfo(Path);    
  75.   
  76.         Response.ClearContent();    
  77.   
  78.         Response.AddHeader("Content-Disposition""attachment; filename=" + file.Name);    
  79.         Response.AddHeader("Content-Length", file.Length.ToString());    
  80.         Response.ContentType = "application/excel";    
  81.         Response.TransmitFile(file.FullName);    
  82.         Response.Flush();    
  83.                           
  84.         RptDoc.Dispose();    
  85.         RptDoc.Close();    
  86.         RptDoc = null;    
  87.           
  88.   
  89.     }    
  90. }   
Step 9 : Here I have created common function for connecting database, and tables. Copy and paste the following code in your .cs file. 
  1. /// <summary>    
  2. /// setDbInfo - for connecting database table     
  3. /// </summary>    
  4. /// <param name="rptDoc">Crystal Report </param>    
  5. /// <param name="ServerName">Database Server name </param>    
  6. /// <param name="DatabaseName">Database name </param>    
  7. /// <param name="UserName">DB Username </param>    
  8. /// <param name="Password">DB Password </param>    
  9. protected void setDbInfo(ReportDocument rptDoc, string Server, string dbName, string UserId, string Pwd)    
  10. {    
  11.     TableLogOnInfo logoninfo = new TableLogOnInfo();    
  12.     // connect multiple tabel    
  13.     foreach (CrystalDecisions.CrystalReports.Engine.Table tbl in rptDoc.Database.Tables)    
  14.     {    
  15.         logoninfo = tbl.LogOnInfo;    
  16.         logoninfo.ReportName = rptDoc.Name;    
  17.         logoninfo.ConnectionInfo.ServerName = Server;    
  18.         logoninfo.ConnectionInfo.DatabaseName = dbName;    
  19.         logoninfo.ConnectionInfo.UserID = UserId;    
  20.         logoninfo.ConnectionInfo.Password = Pwd;    
  21.         logoninfo.TableName = tbl.Name;    
  22.         tbl.ApplyLogOnInfo(logoninfo);    
  23.         tbl.Location = tbl.Name;    
  24.     }    
  25. }   
Step 10 : Now run your application, select PDF and click 'Submit'. It will generate PDF report and if you want Excel Report then select Excel and click on 'Submit' Button.
 
 
 
 
 
 
Here, we have't used CrystalReportViewer for Load and Display Report, Instead we have directly loaded PDF or excel report.

Hope you liked the article.
 

Up Next
    Ebook Download
    View all
    Learn
    View all