Hi kate,
Please refer below sample.
HTML
<asp:HiddenField ID="hfImageData" runat="server" />
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Country:
<asp:DropDownList ID="ddlCountries" runat="server">
<asp:ListItem Text="USA" Value="USA" />
<asp:ListItem Text="Germany" Value="Germany" />
<asp:ListItem Text="France" Value="France" />
<asp:ListItem Text="Brazil" Value="Brazil" />
</asp:DropDownList>
<asp:RadioButtonList ID="rblChartType" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Text="Pie" Value="1" Selected="True" />
<asp:ListItem Text="Doughnut" Value="2" />
</asp:RadioButtonList>
</td>
</tr>
</table>
<div id="dvTable" style="background-color: White; padding: 5px; width: 50%;">
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="OrderID" />
<asp:BoundField DataField="ShipCity" HeaderText="ShipCity" />
<asp:BoundField DataField="ShipCountry" HeaderText="ShipCountry" />
</Columns>
</asp:GridView>
<hr />
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<div id="dvChart">
</div>
</td>
<td>
<div id="dvLegend">
</div>
</td>
</tr>
</table>
</div>
<br />
<asp:Button ID="btnExportToExcel" Text="Export to Excel" runat="server" OnClick="OnExportToExcel" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/excanvas/r3/excanvas.js" type="text/javascript"></script>
<script src="//cdn.jsdelivr.net/chart.js/0.2/Chart.js" type="text/javascript"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script type="text/javascript">
$(function () {
LoadChart();
$("[id*=ddlCountries]").bind("change", function () {
LoadChart();
});
$("[id*=rblChartType] input").bind("click", function () {
LoadChart();
});
});
function LoadChart() {
var chartType = parseInt($("[id*=rblChartType] input:checked").val());
$.ajax({
type: "POST",
url: "Default.aspx/GetChart",
data: "{country: '" + $("[id*=ddlCountries]").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
$("#dvChart").html("");
$("#dvLegend").html("");
var data = eval(r.d);
var el = document.createElement('canvas');
$("#dvChart")[0].appendChild(el);
//Fix for IE 8
if ($.browser.msie && $.browser.version == "8.0") {
G_vmlCanvasManager.initElement(el);
}
var ctx = el.getContext('2d');
var userStrengthsChart;
switch (chartType) {
case 1:
userStrengthsChart = new Chart(ctx).Pie(data);
break;
case 2:
userStrengthsChart = new Chart(ctx).Doughnut(data);
break;
}
for (var i = 0; i < data.length; i++) {
var div = $("<div />");
div.css("margin-bottom", "10px");
div.html("<span style ='display:inline-block;height:10px;width:10px;background-color:" + data[i].color + "'></span> " + data[i].text);
$("#dvLegend").append(div);
}
setTimeout(function () {
html2canvas([document.getElementById('dvTable')], {
onrendered: function (canvas) {
$("[id*=hfImageData]").val(canvas.toDataURL());
}
});
}, 2000);
},
error: function (response) {
alert(response.responseText);
}
});
}
</script>
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Text;
using System.Web.Services;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Drawing
Imports System.IO
Imports System.Text
Imports System.Web.Services
Code
C#
protected void Page_Load(object sender,EventArgs e)
{
if (!this.IsPostBack)
{
string constring = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("Select Top 5 OrderID,ShipCity,ShipCountry From Orders", con))
{
con.Open();
gvOrders.DataSource = cmd.ExecuteReader();
gvOrders.DataBind();
con.Close();
}
}
}
}
[WebMethod]
public static string GetChart(string country)
{
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = string.Format("select shipcity, count(orderid) from orders where shipcountry = '{0}' group by shipcity", country);
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
sb.Append("[");
while (sdr.Read())
{
sb.Append("{");
System.Threading.Thread.Sleep(50);
string color = String.Format("#{0:X6}", new Random().Next(0x1000000));
sb.Append(string.Format("text :'{0}', value:{1}, color: '{2}'", sdr[0], sdr[1], color));
sb.Append("},");
}
sb = sb.Remove(sb.Length - 1, 1);
sb.Append("]");
con.Close();
return sb.ToString();
}
}
}
}
protected void OnExportToExcel(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64)))
{
System.Drawing.Image image = new Bitmap(stream);
image.Save(Server.MapPath("~/Temp/file.png"));
System.Web.UI.WebControls.Image img1 = new System.Web.UI.WebControls.Image();
img1.ImageUrl = Server.MapPath("~/Temp/file.png");
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
System.Web.UI.WebControls.Table table = new System.Web.UI.WebControls.Table();
TableRow row = new TableRow();
row.Cells.Add(new TableCell());
row.Cells[0].Controls.Add(img1);
table.Rows.Add(row);
table.RenderControl(hw);
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Images.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Response.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
}
}
public override void VerifyRenderingInServerForm(Control control)
{
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constring As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
Using con As SqlConnection = New SqlConnection(constring)
Using cmd As SqlCommand = New SqlCommand("Select Top 5 OrderID,ShipCity,ShipCountry From Orders", con)
con.Open()
gvOrders.DataSource = cmd.ExecuteReader()
gvOrders.DataBind()
con.Close()
End Using
End Using
End If
End Sub
<WebMethod>
Public Shared Function GetChart(ByVal country As String) As String
Dim constr As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Dim query As String = String.Format("select shipcity, count(orderid) from orders where shipcountry = '{0}' group by shipcity", country)
Using cmd As SqlCommand = New SqlCommand()
cmd.CommandText = query
cmd.CommandType = CommandType.Text
cmd.Connection = con
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
Dim sb As StringBuilder = New StringBuilder()
sb.Append("[")
While sdr.Read()
sb.Append("{")
System.Threading.Thread.Sleep(50)
Dim color As String = String.Format("#{0:X6}", New Random().[Next](&H1000000))
sb.Append(String.Format("text :'{0}', value:{1}, color: '{2}'", sdr(0), sdr(1), color))
sb.Append("},")
End While
sb = sb.Remove(sb.Length - 1, 1)
sb.Append("]")
con.Close()
Return sb.ToString()
End Using
End Using
End Using
End Function
Protected Sub OnExportToExcel(ByVal sender As Object, ByVal e As EventArgs)
Dim base64 As String = Request.Form(hfImageData.UniqueID).Split(","c)(1)
Using stream As MemoryStream = New MemoryStream(Convert.FromBase64String(base64))
Dim image As System.Drawing.Image = New Bitmap(stream)
image.Save(Server.MapPath("~/Temp/file.png"))
Dim img1 As System.Web.UI.WebControls.Image = New System.Web.UI.WebControls.Image()
img1.ImageUrl = Server.MapPath("~/Temp/file.png")
Using sw As StringWriter = New StringWriter()
Using hw As HtmlTextWriter = New HtmlTextWriter(sw)
Dim table As System.Web.UI.WebControls.Table = New System.Web.UI.WebControls.Table()
Dim row As TableRow = New TableRow()
row.Cells.Add(New TableCell())
row.Cells(0).Controls.Add(img1)
table.Rows.Add(row)
table.RenderControl(hw)
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=Images.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Response.Write(sw.ToString())
Response.Flush()
Response.[End]()
End Using
End Using
End Using
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub
Screenshot
Output