In this article I will explain with an example, how we can create charts in Excel File programmatically from code using ASP.Net Chart Control with C# and VB.Net.
The Chart control can be easily populated from database using DataTable.
HTML Markup
Below is the HTML Markup of the page in which I have an ASP.Net Chart control using which I’ll create a Pie Chart and a Button to trigger the Export to Excel process.
<asp:Label ID="Label1" runat="server" Text="Fruits Distribution (India)" ForeColor = "Red"></asp:Label>
<br />
<asp:Chart ID="Chart1" runat="server" Height="300px" Width="400px">
        <asp:Title ShadowOffset="3" Name="Items" />
        <asp:Legend Alignment="Center" Docking="Bottom" IsTextAutoFit="False" Name="Default"
            LegendStyle="Row" />
        <asp:Series Name="Default" />
       <asp:ChartArea Name="ChartArea1" BorderWidth="0" />
<br />
<asp:Button ID="btnExportExcel" runat="server" Text="Export to Excel" OnClick="btnExportExcel_Click" />
Web.Config File Modifications
You will need to do the following Web.Config file modifications marked in Yellow.
Note: The properties deleteAfterServicing and privateImages are most important in case of export to Excel as otherwise in Excel File you will not see the Chart Image. Thus make sure these properties are always set to false.
        <add key="ChartImageHandler" value="storage=file;timeout=20;deleteAfterServicing=false;privateImages=false" />
        <compilation debug="true" targetFramework="4.0">
                <add assembly="System.Web.DataVisualization, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
                <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
            <remove name="ChartImageHandler" />
            <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST"
                 path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        <validation validateIntegratedModeConfiguration="false" />
You will need to import the following namespaces.
using System.IO;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Web.UI.DataVisualization.Charting;
Imports System.IO
Imports System.Drawing
Imports System.Text.RegularExpressions
Imports System.Web.UI.DataVisualization.Charting
Populating the Pie Chart from DataTable using ASP.Net Chart Control
Below is the code to populate a Pie chart from a DataTable which has been filled with sample data.
Note: If you want to learn about populating ASP.Net Chart from database. Refer Populate ASP.Net 4.0 Chart Control Pie Chart from SQL Server Database.
protected void Page_Load(object sender, EventArgs e)
    string[] x = new string[4] { "Mango", "Apple", "Orange", "Banana" };
    int[] y = new int[4] { 200, 112, 55, 96 };
    Chart1.Series[0].Points.DataBindXY(x, y);
    Chart1.Series[0].ChartType = SeriesChartType.Pie;
    Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
    Chart1.Legends[0].Enabled = true;
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim x() As String = New String() {"Mango", "Apple", "Orange", "Banana"}
    Dim y() As Integer = New Integer() {200, 112, 55, 96}
    Chart1.Series(0).Points.DataBindXY(x, y)
    Chart1.Series(0).ChartType = SeriesChartType.Pie
    Chart1.ChartAreas("ChartArea1").Area3DStyle.Enable3D = True
    Chart1.Legends(0).Enabled = True
End Sub
Export ASP.Net Chart to Excel Worksheet in ASP.Net
Below is the event handler that will export the ASP.Net Chart control to Excel Sheet using ASP.Net. Firstly I need to render the Chart control and fetch the URL of the Chart Image. Then I convert the Relative URL of the chart image as Absolute (This is very necessary as otherwise the Excel file will not show chart image).
In the next step I make use of ASP.Net table control to which I add a Label control as Caption of the Chart and the HTML string of the chart image that I have fetched from the Chart control.
Finally the table is rendered as HTML string and is exported to Excel sheet.
protected void btnExportExcel_Click(object sender, EventArgs e)
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment;filename=ChartExport.xls");
    Response.ContentType = "application/";
    Response.Charset = "";
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    string src = Regex.Match(sw.ToString(), "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase).Groups[1].Value;
    string img = string.Format("<img src = '{0}{1}' />", Request.Url.GetLeftPart(UriPartial.Authority), src);
    Table table = new Table();
    TableRow row = new TableRow();
    row.Cells.Add(new TableCell());
    row.Cells[0].Width = 200;
    row.Cells[0].HorizontalAlign = HorizontalAlign.Center;
    row.Cells[0].Controls.Add(new Label { Text = "Fruits Distribution (India)", ForeColor = Color.Red });
    row = new TableRow();
    row.Cells.Add(new TableCell());
    row.Cells[0].Controls.Add(new Literal { Text = img });
    sw = new StringWriter();
    hw = new HtmlTextWriter(sw);
Protected Sub btnExportExcel_Click(sender As Object, e As EventArgs)
    Response.Buffer = True
    Response.AddHeader("content-disposition", "attachment;filename=ChartExport.xls")
    Response.ContentType = "application/"
    Response.Charset = ""
    Dim sw As New StringWriter()
    Dim hw As New HtmlTextWriter(sw)
    Dim src As String = Regex.Match(sw.ToString(), "<img.+?src=[""'](.+?)[""'].+?>", RegexOptions.IgnoreCase).Groups(1).Value
    Dim table As String = "<table><tr><td><img src='{0}' /></td></tr></table>"
    table = String.Format(table, Request.Url.GetLeftPart(UriPartial.Authority) + src)
End Sub
Dynamically Create Charts in Excel File using ASP.Net Chart Control using C# and VB.Net