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 or 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 exporting. If we export to PDF format, Acrobat can handle the printing for us, as well as saving 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

public class WebForm1 : System.Web.UI.Page
{
protected CrystalDecisions.Web.CrystalReportViewer CrystalReportViewer1;
protected System.Web.UI.WebControls.Button Button1;
private CrystalReport1 report = new CrystalReport1();
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
CrystalReportViewer1.ReportSource = report;
CrystalReportViewer1.Visible =
true;
}
......

Now, all we need to do is to add the event handler for the export button and the code should look like this.

private void Button1_Click(object sender, System.EventArgs e)
{
MemoryStream oStream;
// using System.IO
oStream = (MemoryStream)
report.ExportToStream(
CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
Response.Clear();
Response.Buffer=
true;
Response.ContentType = "application/pdf";
Response.BinaryWrite(oStream.ToArray());
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 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.

Up Next
    Ebook Download
    View all
    Learn
    View all