如何将mschart图表导出为ex​​cel?

时间:2011-08-20 10:00:55

标签: asp.net mschart microsoft-chart-controls

我已经使用Mschart创建了一个图表。我想将创建的图表导出为ex​​cel。 我正在使用以下代码但是当我在excel中打开它时,我只看到一些未知代码而不是图表。

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();

}

3 个答案:

答案 0 :(得分:0)

我发现了同样的问题,经过多次尝试,我找到了正确的方法。这对我有用,代码如下。

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();

希望这有帮助。

答案 1 :(得分:0)

我也在我的一个项目中遇到过这种情况。

这是解决方案。

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

答案 2 :(得分:0)

为您的全球化添加此代码,这对我有用。

        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