Thursday, February 21, 2013

Develop chart in ASP.NET with export to Excel and PDF for MS Excel as well as Open Office

Recently while working on one project in ASP.NET 4.0, i came across a scenario where i had to develop one chart which can be exported to PDF and Excel. Apart from this it has to be viewable in both MS Office and Open Office.


Let us try to develop this functionality.
 
Create a new empty web application and add a new webpage Chart.aspx.

ASP.NET 4.0 comes with a new chart control as shown below.




Go to tool box and drag Chart control on the page.
Now specify the datasource. Here i am using sqldatasource and a view of northwind database to demonstrate the issue. 

















 

Now build the application and run Chart.aspx page.

As seen above, chart has been generated successfully. But, now we want to export above chart in PDF or Excel.

First, let us see how to export above chart to excel.

Let us add one button in the page. Add following event in the button.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace ReportView
{
    public partial class Chart : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        protected void btnExportToExcel_Click(object sender, EventArgs e)
        {
            string attachment = "attachment; filename=Chart.xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            chart.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
    }
}


Now run the page and click on Export to Excel button. Excel will be generated.
Save the excel file and open it in MS Office. You will see that it has added one image tag of chart but actually image is not rendered.

There is one workaround for this. Add following event in the button.

protected void btnExportToExcel_Click(object sender, EventArgs e)
        {
            string tmpChartName = "ChartImage.jpg";
            string imgPath = HttpContext.Current.Request.PhysicalApplicationPath + tmpChartName;
            chart.SaveImage(imgPath);

            string imgPath2 = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/" + tmpChartName);
            Response.Clear();
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", "attachment; filename=Chart.xls;");
            StringWriter stringWrite = new StringWriter();
            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            string headerTable = @"     
";
            Response.Write(headerTable);
            Response.Write(stringWrite.ToString());
            Response.End();
        }

 

Here we are first saving the chart as image. After saving the image we are creating one html with a table with single tr and td tag and an image tag inside that td tag. We are then binding the generated chart image to the img tag as shown above.

Build the application and click on Export to Excel button. Excel will be generated.
Save the excel file and open in MS Office. Chart will be displayed in the excel file.

But there is one issue. If you don't have MS office installed and you are using Open Office, then nothing will be displayed in the generated excel file.

Let us try to change the MIME type in above code and try to export the chart.

Response.ContentType = "application/vnd.oasis.opendocument.spreadsheet";
Response.AddHeader("Content-Disposition", "attachment; filename=Chart.ods;"); 

You will see that the chart is not getting exported in Open Office spreadsheet.

Also, what if you want to export above chart to pdf? Specifying MIME for pdf in above code will not work.

So directly using chart control in your page has got some limitations. The solution for this is simple.

Remove the chart control from page and add local RDLC report.

 
Drag chart control from toolbox displayed in rdlc report and specify the datasource and view for the chart.

 
Save the report and goto Chart.aspx page.

Add one ReportViewer control and ScriptManager control in the page and specify the Chart.rdlc report in the report viewer.











 

Specify the datasource in reportviewer to northwind sqldatasource and run the page.
Chart will be displayed as shown below:

In the toolbar of reportviewer there are options for export to Excel, PDF and Word.
After exporting chart can be clearly viewed in MS Office as well as Open Office.
Chart can also be exported to PDF without any issue.

Thus our task is accomplished without using any third party components. Thanks to reportviewer control.

 
 
 

 

Wednesday, February 10, 2010

Inheritance, Abstract Classes, Polymorphism

What is a class?
A class is a blue print or template of real world objects.
E.g. Consider a class Vehicle, which defines properties and behaviour of a vehicle like Vehicle Type, Name, Color, Accelerate, etc. where Vehicle Type, Name and Color are properties and Accelerate is a behaviour or functionality.
What is an object?
An object is an instance of a class. It represents real world entity. E.g. My Bajaj Pulsar is an object of type Vehicle which is a class.
What is inheritance?
It is an OOPS concept in which a class reuses properties and behaviour of some other class(base class). Along with that it also defines its own behaviour and properties.
What is an abstract class?
An abstract class is declared with keyword "abstract".
You cannot create an instance of an abstract class.
Abstract classes have atleast one abstract method or property. Abstract methods and properties don't have implementations.
e.g.
public abstract class Employee
{
//Abstract method
public abstract void AssignWork(string Name);
//Non abstract method
public string GetSalary(string Name)
{
//Logic for getting salary
return string.Empty;
}
}
Above class is an abstract class since it has an abstract method which is not having its implementation.
If you have an abstract method or property in your class and you don't declare that class as abstract, it would give compilation error.
An abstract class can also have non-abstract methods or properties. It is not necessary that all the methods and properties in abstract class are abstract.
Abstract classes are generally used when you have a requirement where you want to have some
functionality being implemented in similar way along with some other functionality to be implemented in different way.
e.g. consider above abstract class Employee and consider two types of class Developers and Testers which inherit from Employee.
Method of getting the salary of Developers and Testers would be same. So i have declared it non-abstract method. But the process of assigning work to both would be different. So i have declared AssignWork method as abstract. This method is not implemented in base class but will be implemented in Developers and Testers class.
To implement this abstract method, override keyword is used in child class. This is called Method Overriding.
e.g.

public class Developers : Employee
{
public override void AssignWork(string Name)
{
//Logic for assigning work to developers.
}
}
Now create an instance of Developers class and implement its methods.
public void Main()
{
Developers employee = new Developers();
string salary = employee.GetSalary("Haseet");
employee.AssignWork("Haseet");
}
As you can see, GetSalary method is shared between Developers and Testers class, while AssignWork is defined by both. This process of having two different behaviours but with same name is called Polymorphism.