0

I have created a chart with Mschart.I want to export the created chart to excel. I'm using following code but when I open it in excel I just see some unknown code instead of chart.

using (var chartimage = new MemoryStream())
{
    ChartAmalkerd.SaveImage(chartimage, ChartImageFormat.Png);
    ExportToExcel(chartimage.GetBuffer());
}
private void ExportToExcel(byte[] input)
{
    string attachment = "attachment; filename=Employee.xls";
    Response.ClearContent();
    Response.ContentEncoding = Encoding.GetEncoding(1256);
    Response.AddHeader("content-disposition", attachment);
    Response.ContentType = "application/vnd.ms-excel";
    Response.Buffer = true;
    this.EnableViewState = false;
    Response.BinaryWrite(input);
    Response.Flush();
    Response.Close();
    Response.End();

}
digEmAll
  • 56,430
  • 9
  • 115
  • 140
Raymond Morphy
  • 2,464
  • 9
  • 51
  • 93

3 Answers3

0

I have found the same issue and after making several attempts, I was able to find out the correct way. This worked for me and the code is as follows.

string tmpChartName = "test2.jpg";
    string imgPath = HttpContext.Current.Request.PhysicalApplicationPath + tmpChartName;

    Chart1.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=test.xls;");
    StringWriter stringWrite = new StringWriter();
    HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    string headerTable = @"<Table><tr><td><img src='" + imgPath2 + @"' \></td></tr></Table>";
    Response.Write(headerTable);
    Response.Write(stringWrite.ToString());
    Response.End();

Hope this helps.

Sugandika
  • 772
  • 5
  • 10
  • I am not able to see the chart in excel sheet. Virtualpathutility plays any part in this.? – Ankur Jul 25 '13 at 06:38
0

I also came across such scenario in one of my project.

Here is the solution.

http://haseet.blogspot.in/2013/02/develop-chart-in-aspnet-with-export-to-excel-pdf-msoffice-openoffice.html

0

Add this code for your globalization, this works for me.

        Dim info As System.Globalization.CultureInfo = New System.Globalization.CultureInfo("en-US")
        Thread.CurrentThread.CurrentCulture = info
        Thread.CurrentThread.CurrentUICulture = info
        context.Response.ContentEncoding = System.Text.Encoding.UTF8
        context.Response.HeaderEncoding = System.Text.Encoding.UTF8