Click here to Skip to main content
12,452,066 members (25,292 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

156.7K views
7.2K downloads
23 bookmarked
Posted

How to Export Crystal Report on Button Click in to PDF, Excel, Word, HTML, Rtf in ASP.NET C#.

, 27 Jan 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
This article discusses how to export Crystal Report on button click into PDF, Excel, Word, HTML, RTF in ASP.NET C#

Introduction

What Is Crystal Reports?

"In simplest terms, Crystal Reports is a report design tool that allows you to create reports capable of retrieving and formatting a result set from a database or other data source. In addition to simply reading data from a data source, Crystal Reports has its own formula language for creating calculations and includes a number of features that can be used to turn raw data into presentation-quality reports, with graphs, charts, running totals, and so on." (David McAmis, Professional Crystal Reports for Visual Studio .NET, 2nd edition)

We give this option to users to download there on copy of result what they want from search result.

Sqlserver Part

Create a Simple Table Name as PersonInfo :

create Table PersonInfo
(
PersonID int primary key IDENTITY(1,1) NOT NULL,
PersonName Nvarchar(100) NULL,
PersonAge int NULL,
PersonAddress Nvarchar(100) NULL,
PersonProfession nvarchar(100) NULL
)



Inserting Records  

Insert Records into Table from backend

  

Selecting Records for displaying on report Using StoredProcedure

CREATE Proc Usp_getPersonRecords
as
SELECT * FROM PersonInfo   

Create a new ASP.NET Web Application Project.





Add New Web form -> Name it as ExportRecords.aspx.


Adding Crystal Report




When this Screen appears in front of you, just select (Standard) and Press Ok button.


The Standard Report Creation Wizard will pop


Select Create New Connection.  

  1. Inside That OLE DB
  2. A new Wizard will pop up OLE DB (ADO)



  3. It will ask for Provider
  4. Select (Microsoft OLE DB Provider for SQL Server)
  5. Click Next Button


Connection Information Wizard will appear.  

Just enter your SQL Server details here.

 

Then click on Next button

 

After click on Finish this wizard will appear.

 

  1. First select your Database where you have created table.
  2. Inside that you will find 3 options  
    1. dbo  
    2. INFORMATION_SCHEMA
    3. Sys  
  3. Select dbo (Here you will see 2 options)
    1. Tables
    2. Stored procedures
  4. Select Store procedures from it.

(Because we will bind Store procedures to report to display information)

 

The Store procedures Usp_getPersonRecords will appear in the list of data sources, add the Store procedures to selected table list by clicking on the right arrow.

Click Next button

This wizard will appear.

 

Select all columns and then clicking on the right arrow to move in Fields to Display

 

Click on Next Button

 

We will not perform Grouping Just click Next Button

This wizard will appear.

 

We will not perform Record Filter Just click Next Button

This wizard will appear.

 

Select Standard from it and click Finish.

After Finishing the crystal report will appear to you.

 

Just Save it.  

Let’s Move from sql to Web forms now. (ExportRecords.aspx)

On Page Add Crystal Report viewer and three images buttons

(I have add images to buttons)  

<form id="form1" runat="server">
<div style="margin: 0px; overflow: auto;">
<table width="100%">
<tr>
<td align="center">

<asp:ImageButton ID="Img1" Height="50px" ImageUrl="~/Images/PdfImage.jpg"
runat="server" onclick="Img1_Click" />

<asp:ImageButton ID="img2" Height="50px" ImageUrl="~/Images/index.jpg"
runat="server" onclick="img2_Click" />

<asp:ImageButton ID="img3" Height="50px" ImageUrl="~/Images/docx.png"
runat="server" onclick="img3_Click" />

<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" />

</td>
</tr>
</table>
</div>
</form>

Like this View you will see

 

On load for Binding crystal Report i have created Method GenerateReport().

You need to add Connection string above Page load.

SqlConnection con = new SqlConnection
(ConfigurationManager.ConnectionStrings["Myconstr"].ToString());

And add Connection string In Web.config.

For doing connection with database you need to add connection string to database Here is example of it.

Just replace here with your database value.

Data source

Database

User id

Password

<connectionStrings>
   <add name="Myconstr" connectionString="data source=SAI-PC; Database=MotorTraining;  user id=sa; password=Pass$123 ;" providerName="system.data.sqlclient"/>
</connectionStrings>

Here I have bind crystal report on page load event.

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GenerateReport();
            }
        }

This is method which I am using for binding crystal report on page load.

protected void GenerateReport()
        {
            SqlCommand cmd = new SqlCommand("Usp_getPersonRecords", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataTable datatable = new DataTable();
            da.Fill(datatable); // getting value according to imageID and fill dataset

            ReportDocument crystalReport = new ReportDocument(); // creating object of crystal report
            crystalReport.Load(Server.MapPath("~/CrystalPersonInfo.rpt")); // path of report 
            crystalReport.SetDataSource(datatable); // binding datatable
            CrystalReportViewer1.ReportSource = crystalReport;
        }

How It Works

On button click we are going to Export crystal report in pdf, Excel, html, format.

We are bringing all data from sql server into dataset and binding dataset to crystal report data source.

Creating object of report document

ReportDocument crystalReport = new ReportDocument();

After creating object we are going to load crystal report by giving its path.

crystalReport.Load(Server.MapPath("~/CrystalPersonInfo.rpt"));

Here we are assigning format to export.

crystalReport.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, 
    Response, true, "PersonDetails");

First Button (Img1 for exporting records in PDF format)

On button click we are going to Export crystal report in PDF format.

protected void Img1_Click(object sender, ImageClickEventArgs e)
        {
            SqlCommand cmd = new SqlCommand("Usp_getPersonRecords", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataTable datatable = new DataTable();
            da.Fill(datatable); // getting value according to imageID and fill dataset

            ReportDocument crystalReport = new ReportDocument(); // creating object of crystal report
            crystalReport.Load(Server.MapPath("~/CrystalPersonInfo.rpt")); // path of report 
            crystalReport.SetDataSource(datatable); // binding datatable
            CrystalReportViewer1.ReportSource = crystalReport;

            crystalReport.ExportToHttpResponse
            (CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Response, true, "PersonDetails");
            //here i have use [ CrystalDecisions.Shared.ExportFormatType.PortableDocFormat ] to Export in PDF

        }

First Second (Img2 for exporting records in Excel format)

On button click we are going to Export crystal report in Excel format.

protected void img2_Click(object sender, ImageClickEventArgs e)
        {
            SqlCommand cmd = new SqlCommand("Usp_getPersonRecords", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataTable datatable = new DataTable();
            da.Fill(datatable); // getting value according to imageID and fill dataset

            ReportDocument crystalReport = new ReportDocument(); // creating object of crystal report
            crystalReport.Load(Server.MapPath("~/CrystalPersonInfo.rpt")); // path of report 
            crystalReport.SetDataSource(datatable); // binding datatable
            CrystalReportViewer1.ReportSource = crystalReport;

            crystalReport.ExportToHttpResponse
            (CrystalDecisions.Shared.ExportFormatType.ExcelRecord, Response, true, "PersonDetails");
            //here i have use [ CrystalDecisions.Shared.ExportFormatType.ExcelRecord ] to Export in Excel
        }

First Third (Img3 for exporting records in Word format)

On button click we are going to Export crystal report in Word format

protected void img3_Click(object sender, ImageClickEventArgs e)
        {
            SqlCommand cmd = new SqlCommand("Usp_getPersonRecords", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataTable datatable = new DataTable();
            da.Fill(datatable); // getting value according to imageID and fill dataset

            ReportDocument crystalReport = new ReportDocument(); // creating object of crystal report
            crystalReport.Load(Server.MapPath("~/CrystalPersonInfo.rpt")); // path of report 
            crystalReport.SetDataSource(datatable); // binding datatable
            CrystalReportViewer1.ReportSource = crystalReport;

            crystalReport.ExportToHttpResponse
            (CrystalDecisions.Shared.ExportFormatType.WordForWindows, Response, true, "PersonDetails");
            //here i have use [ CrystalDecisions.Shared.ExportFormatType.WordForWindows ] to Export in Word
        }

Now save and run project.  

All records will appear on Crystal report.

With five buttons to Export.

 

On clicking of PDF button.

 

On clicking Excel button.



On clicking of Word button.



 

On clicking of HTML button.

 

On clicking of RTF button

 

Making Easy to Understand

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

saineshwar
Software Developer Mahaonline LTD
India India
Indian Software Developer and MVP from c-sharpcorner working on .Net Web Technology
( Asp.net , C# , Sqlserver , MVC , Windows ,Console Application, javascript , jquery , json , ORM Dapper) and also freelance developer.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionAdding the code to existing report Pin
Thameera Nawaratna24-Mar-16 22:28
professionalThameera Nawaratna24-Mar-16 22:28 
AnswerRe: Adding the code to existing report Pin
saineshwar25-Mar-16 20:15
membersaineshwar25-Mar-16 20:15 
GeneralRe: Adding the code to existing report Pin
Thameera Nawaratna28-Mar-16 21:09
professionalThameera Nawaratna28-Mar-16 21:09 
QuestionError Pin
Praveen SKumar16-Mar-16 21:15
memberPraveen SKumar16-Mar-16 21:15 
AnswerRe: Error Pin
saineshwar25-Mar-16 20:19
membersaineshwar25-Mar-16 20:19 
GeneralRe: Error Pin
Praveen SKumar5-Apr-16 0:58
memberPraveen SKumar5-Apr-16 0:58 
QuestionExport CrystalDocument in c# Pin
Rushabhs99916-Mar-16 20:16
memberRushabhs99916-Mar-16 20:16 
AnswerRe: Export CrystalDocument in c# Pin
saineshwar16-Mar-16 20:33
membersaineshwar16-Mar-16 20:33 
AnswerRe: Export CrystalDocument in c# Pin
saineshwar25-Mar-16 20:20
membersaineshwar25-Mar-16 20:20 
QuestionDo this code still works with CR 13 or it throws exception like mine. Pin
Harcheem25-Jun-15 16:48
memberHarcheem25-Jun-15 16:48 
AnswerRe: Do this code still works with CR 13 or it throws exception like mine. Pin
Harcheem25-Jun-15 17:02
memberHarcheem25-Jun-15 17:02 
GeneralRe: Do this code still works with CR 13 or it throws exception like mine. Pin
saineshwar25-Jun-15 17:36
membersaineshwar25-Jun-15 17:36 
GeneralRe: Do this code still works with CR 13 or it throws exception like mine. Pin
Harcheem27-Jun-15 13:45
memberHarcheem27-Jun-15 13:45 
QuestionGenerating crystal reports in mvc 4 Pin
Member 1134525229-Apr-15 3:01
memberMember 1134525229-Apr-15 3:01 
QuestionThanks Pin
Mei Yi16-Feb-15 16:45
memberMei Yi16-Feb-15 16:45 
QuestionHow to convert crystal report file into .pdf file Pin
Shemeemsha (ഷെമീംഷ)15-Jan-15 1:54
memberShemeemsha (ഷെമീംഷ)15-Jan-15 1:54 
QuestionExporting to html Page headers are missing Pin
Member 106783484-Aug-14 20:04
memberMember 106783484-Aug-14 20:04 
QuestionExport Three crystal report in one PDF file at a time Pin
Ajay Shedge13-Jul-14 23:52
professionalAjay Shedge13-Jul-14 23:52 
AnswerRe: Export Three crystal report in one PDF file at a time Pin
saineshwar16-Jul-14 18:51
membersaineshwar16-Jul-14 18:51 
GeneralRe: Export Three crystal report in one PDF file at a time Pin
Ajay Shedge16-Jul-14 19:24
professionalAjay Shedge16-Jul-14 19:24 
GeneralRe: Export Three crystal report in one PDF file at a time Pin
saineshwar16-Jul-14 19:41
membersaineshwar16-Jul-14 19:41 
GeneralRe: Export Three crystal report in one PDF file at a time Pin
Ajay Shedge18-Jul-14 18:44
professionalAjay Shedge18-Jul-14 18:44 
GeneralRe: Export Three crystal report in one PDF file at a time Pin
saineshwar19-Jul-14 3:26
membersaineshwar19-Jul-14 3:26 
GeneralRe: Export Three crystal report in one PDF file at a time Pin
Ajay Shedge25-Jul-14 21:55
professionalAjay Shedge25-Jul-14 21:55 
GeneralRe: Export Three crystal report in one PDF file at a time Pin
saineshwar26-Jul-14 20:55
membersaineshwar26-Jul-14 20:55 
GeneralRe: Export Three crystal report in one PDF file at a time Pin
Ajay Shedge27-Jul-14 19:10
professionalAjay Shedge27-Jul-14 19:10 
QuestionWhat about Parameters? Pin
Liefie200013-May-14 5:03
memberLiefie200013-May-14 5:03 
AnswerRe: What about Parameters? Pin
saineshwar13-May-14 6:14
membersaineshwar13-May-14 6:14 
GeneralRe: What about Parameters? Pin
Liefie200013-May-14 6:19
memberLiefie200013-May-14 6:19 
GeneralRe: What about Parameters? Pin
Liefie200013-May-14 9:16
memberLiefie200013-May-14 9:16 
GeneralRe: What about Parameters? Pin
saineshwar13-May-14 19:00
membersaineshwar13-May-14 19:00 
AnswerRe: What about Parameters? Pin
robertgalp26-Jun-14 20:01
memberrobertgalp26-Jun-14 20:01 
QuestionHow to use the data source with subreports Pin
sukeshchand23-Mar-14 21:29
professionalsukeshchand23-Mar-14 21:29 
AnswerRe: How to use the data source with subreports Pin
saineshwar23-Mar-14 23:01
membersaineshwar23-Mar-14 23:01 
GeneralRe: How to use the data source with subreports Pin
sukeshchand25-Mar-14 7:16
professionalsukeshchand25-Mar-14 7:16 
GeneralRe: How to use the data source with subreports Pin
saineshwar25-Mar-14 17:59
membersaineshwar25-Mar-14 17:59 
AnswerRe: How to use the data source with subreports Pin
saineshwar23-Mar-14 23:04
membersaineshwar23-Mar-14 23:04 
QuestionHow to get page headers exporting to html format Pin
Member 1067834819-Mar-14 3:06
memberMember 1067834819-Mar-14 3:06 
AnswerRe: How to get page headers exporting to html format Pin
Member 106783484-Aug-14 20:06
memberMember 106783484-Aug-14 20:06 
Questionabout using this with unicode characters Pin
pratt133226-Feb-14 7:55
memberpratt133226-Feb-14 7:55 
AnswerRe: about using this with unicode characters Pin
saineshwar26-Feb-14 19:11
membersaineshwar26-Feb-14 19:11 
AnswerRe: about using this with unicode characters Pin
saineshwar25-Mar-14 18:01
membersaineshwar25-Mar-14 18:01 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun27-Jan-14 19:53
memberHumayun Kabir Mamun27-Jan-14 19:53 
GeneralRe: My vote of 5 Pin
saineshwar13-Feb-14 20:48
membersaineshwar13-Feb-14 20:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160826.1 | Last Updated 27 Jan 2014
Article Copyright 2014 by saineshwar
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid