2012-05-16 34 views
0

我使用MS圖表控件在我的Web應用程序(.Net 4.0)中生成了一個圖表。我的要求是將特定圖表導出爲Excel文件作爲圖像。我寫了下面提到的代碼,試圖將圖表圖像作爲字節數組寫入excel文件。但是在我的excel文件中導致了一些未知的字符。 (字節數組可能已經直接寫入文件)。如何將MS圖表控件導出到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文件嗎? (不使用字節數組也可以) 謝謝

+1

你將有實際創建電子表格第一,而不是試圖只是將圖像保存爲.xls!嘗試[其中一個庫](http://stackoverflow.com/questions/151005/create-excel-xls-and-xlsx-file-from-c-sharp) – Rup

+0

@RUP - 非常感謝您的快速響應和建議。我很高興地說,我已經找到了正確實施它的方法。我將分享我的源代碼,以便每個人都可以瞭解它。再次感謝 – Sugandika

回答

0

我能夠找到正確的方式來實現它;導出ms圖表(ms圖表控件)作爲圖像優秀。我很高興在這裏分享。正確的源代碼示例如下。

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

謝謝:)

+0

嗯,這仍然不是一個真正的Excel文件 - 你現在將HTML發佈爲.XLS而不是實際的.XLS。並且你的解決方案不支持多個併發用戶:如果你要走這條路線,最好有另一個控制器生成並返回圖像,然後讓這個控制器生成一個URL。但是我仍然認爲你應該創建一個真正的XLS文件而不是HTML。 – Rup

+0

@RUP - 非常感謝您的想法。我會考慮它以提出更好的解決方案。 – Sugandika

相關問題