c#怎么在word里生成图表啊
从数据表里读出来一些数据,想在word里面以这些数据生成饼状图的统计表,怎么做呀?急急急!!!
------解决方案--------------------
1.先去網路上找OWC11.OCX控件,找到後下載至電腦。
2.開啟CMD使用REGSVR32來註冊此控件。
3.完成後,開啟您的VS/功能列/工具/選擇工具箱項目/COM元件/勾選Microsoft Office Chart 11.0/確定
4.回到你的應用程式開發介面,將Microsoft Office Chart 11.0引用至UI,即可開始編碼
如
private AxMicrosoft.Office.Interop.Owc11.AxChartSpace ChartSpace1;
private Microsoft.Office.Interop.Owc11.ChChart Chart1;
private void Form1_Load(object sender, EventArgs e)
{
StartPaint_Chart(this.axChartSpace1);
}
private void StartPaint_Chart(AxMicrosoft.Office.Interop.Owc11.AxChartSpace axChartSpace)
{
axChartSpace.Clear();
//定義您的數據,並轉型為Object之後Chart才可讀取
object[] isDateTime = new object[] { "一月", "二月", "三月", "四月", "五月", "六月"};
object[] VBSerice = new object[] { "20", "15", "41", "10", "21", "5" };
//
ChartSpace1 = this.axChartSpace1;
Chart1 = ChartSpace1.Charts.Add(0);
Chart1.HasTitle = true;
Chart1.Title.Caption = "餅圖";
Chart1.Title.Font.Size = 10;
Chart1.Title.Font.Bold = true;
Chart1.Title.Font.Color = "white";
Chart1.PlotArea.Interior.Color = "black";
Chart1.PlotArea.Border.Color = "white";
Chart1.Interior.Color = "black";
Chart1.Axes[0].Font.Color = "yellow";
Chart1.Axes[0].Line.Color = "white";
Chart1.SeriesCollection.Add(0);
Chart1.SeriesCollection[0].Line.Color = "red";
//圖的類型
Chart1.Type = Microsoft.Office.Interop.Owc11.ChartChartTypeEnum.chChartTypePie;
//定義橫軸並讀入數據
Chart1.SeriesCollection[0].SetData(Microsoft.Office.Interop.Owc11.ChartDimensionsEnum.chDimCategories, (int)Microsoft.Office.Interop.Owc11.ChartSpecialDataSourcesEnum.chDataLiteral, isDateTime);
//定義縱軸並讀入數據
Chart1.SeriesCollection[0].SetData(Microsoft.Office.Interop.Owc11.ChartDimensionsEnum.chDimValues, (int)Microsoft.Office.Interop.Owc11.ChartSpecialDataSourcesEnum.chDataLiteral, VBSerice);
}
------解决方案--------------------
添加引用:Microsoft.Office.Interop.Word 和 Microsoft.Office.Interop.Excel 以及COM组件引用:
Microsoft Office 14.0 Object Library
C# code
using System;
using System.Linq;
using Microsoft.Office.Core;
using Word=Microsoft.Office.Interop.Word;
using Excel=Microsoft.Office.Interop.Excel;
class Program
{
static void Main(string[] args)
{
string title = "市场份额-饼图";
string[] names = { "公司A", "公司B", "公司C", "公司D", "公司E" }; // 数据名称
double[] values = { 10.0, 32.5, 22.4, 34.1, 15.9 }; // 对应数据
int count = names.Length;
var app = new Word.Application();
var doc = app.Documents.Add();
var chart = doc.InlineShapes.AddChart(XlChartType.xl3DPie).Chart;
Excel.Worksheet book = chart.ChartData.Workbook.Worksheets["Sheet1"];
var data = new object[count, 2];
Enumerable.Range(0, count).ToList().ForEach(i => {data[i,0]=names[i]; data[i,1]=values[i];});
book.get_Range("A2", "B"+(count+1)).Value = data;
book.get_Range("B1").Value = title;
doc.SaveAs2(@"d:\test.doc");
app.Quit(true);
}
}