Sunday, October 24, 2021

How to Export Crystal Report in ASP.NET

 When using Crystal Reports in ASP.NET in a Web Form, the CrystalReportViewer control does not have the export of the print buttons like the one in Windows Form. 

We can still achieve some degree of export and print functionality by writing our own code to handle exports. If we export to PDF format, Acrobat can handle the printing for us, as well as save a copy of the report.

 
First, design your Web form, add the Crystal Report Viewer, and a button called "Export". I assume a new crystal report has been created and it's called report.
 
ExportCrystalReport1.jpg
 
So your code will probably look like this now
  1. public class WebForm1: System.Web.UI.Page {  
  2.         protected CrystalDecisions.Web.CrystalReportViewer CrystalReportViewer1;  
  3.         protected System.Web.UI.WebControls.Button Button1;  
  4.         private CrystalReport1 report = new CrystalReport1();  
  5.         private void Page_Load(object sender, System.EventArgs e) {  
  6.                 // Put user code to initialize the page here  
  7.                 CrystalReportViewer1.ReportSource = report;  
  8.                 CrystalReportViewer1.Visible = true;  
  9.             }  
  10.             ...... 
Now, all we need to do is to add the event handler for the export button and the code should look like this.
  1. private void Button1_Click(object sender, System.EventArgs e) {  
  2.     MemoryStream oStream; // using System.IO  
  3.     oStream = (MemoryStream)  
  4.     report.ExportToStream(  
  5.         CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);  
  6.     Response.Clear();  
  7.     Response.Buffer = true;  
  8.     Response.ContentType = "application/pdf";  
  9.     Response.BinaryWrite(oStream.ToArray());  
  10.     Response.End();  
That's all there is. One good thing about this is that no files are written on the server-side. The available formats are PDF, Winword, and Excel, but I think PDF is probably the most useful. You can also add code to dispose of the memory stream and do a garbage collection if you want to ensure that resources are optimally managed.
 
ExportCrystalReport2.jpg
 
That's a sample report on our simple web page
 
ExportCrystalReport3.jpg
 
That's what happens when we click the export button.

No comments:

Post a Comment

No String Argument Constructor/Factory Method to Deserialize From String Value

  In this short article, we will cover in-depth the   JsonMappingException: no String-argument constructor/factory method to deserialize fro...