簡體   English   中英

如何將MS Chart控件導出到Excel

[英]How to export MS Chart control to Excel

我已經使用MS Chart Controls在Web應用程序(.Net 4.0)中生成了一個圖表。 我的要求是將特定的圖表作為圖像導出到Excel文件中。 我寫了下面提到的代碼,試圖將圖表圖像作為字節數組寫入excel文件。 但這導致我的excel文件中出現一些未知字符。 (字節數組可能已直接寫入文件中)。

byte[] bytes2;
    using (var chartimage = new MemoryStream())
    {
        Chart1.SaveImage(chartimage, ChartImageFormat.Png);
        bytes2 = chartimage.GetBuffer();
    }

    Response.Clear();
    Response.ContentType = "application/ms-excel";
    Response.AddHeader("content-disposition", "attachment; filename=StudentResults.xls");
    Response.BinaryWrite(bytes2);

    Response.End();

誰能幫助我以正確的方式將此圖表寫入Excel文件? (不使用字節數組也可以)謝謝

我能夠找到實現它的正確方法。 將ms圖表(ms圖表控件)導出為ex​​cel作為圖像。 很高興在這里分享。 正確的源代碼示例如下。

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

謝謝 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM