c#操作word图表(一)

版权声明:欢迎转载,转载请注明原始出处 https://blog.csdn.net/xiaomingelv/article/details/17185005

c#操作word图表

前阵子接到了一个任务,需要实现一个功能,利用代码在word中插入图表并且插入数据,生成类似于柱状图,饼图,线条之类乱七八糟的东西,关于这个方面,不得不说网上的资料相对较少,多方查找资料之后发现大概有两种方式,一种是利用Microsoft.Office.Interop.Graph.Chart,另外一种是利用Microsoft.Office.Interop.Excel.Chart,二者的区别在于一个需要调用后者需要调用excel,而前者则不需要,但后者在word 07之后的版本显示出来的图表会比前者漂亮,这里主要先贴出第一种的操作方法,第二种插入Excel图表的方法会在另外一篇文章中给出。由于需要在word文档的指定位置上插入图表,所以需要手工在文档中添加标签,然后通过代码寻找相应的标签定位。好了,不说废话,上代码

首先,添加两个引用,Microsoft.Office.Interop.Word,Microsoft.Office.Interop.Graph

/// <summary>
        /// 将图表插入到word文档中
        /// </summary>
        /// <param name="oEndOfDoc">书签</param>
        /// <param name="data">数据源</param>
        /// <param name="height">高</param>
        /// <param name="width">宽</param>
        /// <param name="chartType">图标类型</param>
        /// <param name="path">word文档路径</param>
        public static void AddChartByXiaominge(Object oEndOfDoc, DataSet data, float height, float width, XlChartType chartType, string path,string title)
        {
            object oMissing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Application oWord;

            Microsoft.Office.Interop.Word.Document oDoc = null;

            oWord = new Microsoft.Office.Interop.Word.Application();

            //打开word文档
            try
            {
                oDoc = oWord.Documents.Open(path, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,

                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,

                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            }
            catch (Exception e)
            {
                oWord.Quit(Type.Missing, Type.Missing, Type.Missing);

                throw e;
            }

            //设置word界面为不可见
            oWord.Visible = false;


            if (oWord.ActiveDocument.Bookmarks.Exists(oEndOfDoc.ToString()))
            {
                try
                {
                    //插入chart    
                    Word.InlineShape oShape;
<span style="white-space:pre">		</span>   //此处为插入的图表类型
                    object oClassType = "MSGraph.Chart.8";

                    Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

                    oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing,

                    ref oMissing, ref oMissing, ref oMissing,

                    ref oMissing, ref oMissing, ref oMissing);

                    object oChart = oShape.OLEFormat.Object;

                    object[] Parameters = new Object[1];

                    Parameters[0] = 4;

                    Microsoft.Office.Interop.Graph.Chart objChart = (Microsoft.Office.Interop.Graph.Chart)oShape.OLEFormat.Object;

                    Microsoft.Office.Interop.Graph.Application oChartApp = objChart.Application;

                    objChart.ChartType = chartType;

                    objChart.HasTitle = true;

                    objChart.ChartTitle.Text = title;

                    objChart.ChartTitle.Font.Size = 10;

                    objChart.PlotArea.Interior.Color = Color.White;

                    //绑定数据  
                    DataSheet dataSheet;

                    dataSheet = objChart.Application.DataSheet;

                    dataSheet.Columns.Clear();

                    dataSheet.Rows.Clear();

                    System.Data.DataTable table = data.Tables[0];

                    for (int i = 1; i <= table.Rows.Count + 1; i++)
                    {
                        for (int j = 1; j <= table.Columns.Count; j++)
                        {
                            if (i == 1 && j != 1)
                            {
                                dataSheet.Cells[i, j] = table.Columns[j - 1].ColumnName;
                            }
                            else
                            {
                                if (!(i == 1 && j == 1))
                                {
                                    dataSheet.Cells[i, j] = table.Rows[i - 2][j - 1];
                                }
                            }
                        }
                    }

                    Microsoft.Office.Interop.Graph.Series s;

                    Microsoft.Office.Interop.Graph.UpBars b;

                    if (chartType != XlChartType.xl3DPieExploded)
                    {
                        for (int i = 1; i <= table.Rows.Count; i++)
                        {
                            s = (Microsoft.Office.Interop.Graph.Series)objChart.SeriesCollection(i);

                            s.Shadow = false;
<span style="white-space:pre">				</span>//对图表进行润色
                            if (chartType == XlChartType.xlColumnClustered)
                            {
                                switch (i)
                                {
                                    case 1:
                                        s.Interior.Color=Color.LightBlue;
                                        break;
                                    case 2:
                                        s.Interior.Color = Color.GreenYellow;
                                        break;
                                    case 3:
                                        s.Interior.Color = Color.Khaki;
                                        break;
                                    case 4:
                                        s.Interior.Color = Color.Wheat;
                                        break;
                                    case 5:
                                        s.Interior.Color = Color.DodgerBlue;
                                        break;
                                    case 6:
                                        s.Interior.Color = Color.CornflowerBlue;
                                        break;
                                    case 7:
                                        s.Interior.Color = Color.LightYellow;
                                        break;
                                    default:
                                        s.Interior.ColorIndex = 6 * i + 6;
                                        break;

                                }
                               
                            }

                            s.HasDataLabels = true;

                            s.DataLabels().Font.Size = 5;
                        }

                        objChart.Legend.Position = Microsoft.Office.Interop.Graph.XlLegendPosition.xlLegendPositionTop;

                        objChart.Legend.Height = 15;

                        objChart.Legend.Width = 150;

                        objChart.Legend.Left = objChart.ChartArea.Width / 2 - objChart.Legend.Width/2;
                    }
                    else
                    {
                        objChart.HasLegend = false;

                        s = (Microsoft.Office.Interop.Graph.Series)objChart.SeriesCollection(1);
<span style="white-space:pre">			</span>//
                        for (int i = 1; i < table.Columns.Count; i++)
                        {
                            switch (i)
                            {
                                case 1:
                                    s.Points(i).Interior.Color = Color.LightBlue;
                                    break;
                                case 2:
                                    s.Points(i).Interior.Color = Color.GreenYellow;
                                    break;
                                case 3:
                                    s.Points(i).Interior.Color = Color.Khaki;
                                    break;
                                case 4:
                                    s.Points(i).Interior.Color = Color.Wheat;
                                    break;
                                case 5:
                                    s.Points(i).Interior.Color = Color.DodgerBlue;
                                    break;
                                case 6:
                                    s.Points(i).Interior.Color = Color.CornflowerBlue;
                                    break;
                                case 7:
                                    s.Points(i).Interior.Color = Color.LightYellow;
                                    break;
                                default:
                                    s.Points(i).Interior.ColorIndex = 6 * i + 6;
                                    break;

                            }
                        }

                        s.HasDataLabels = true;

                        //显示引导线
                        objChart.SeriesCollection(1).HasLeaderLines = true;

                        //显示百分比
                        s.DataLabels().ShowPercentage = true;

                        s.DataLabels().Font.Size = 6;

                        //显示分组名
                        s.DataLabels().ShowCategoryName = true;

                        //不显示数值
                        s.DataLabels().ShowValue = false;
                    }

                    objChart.Application.Update();

                    oChartApp.Update();

                    oChartApp.Quit();

                    //宽
                    oShape.Width = width;

                    //高
                    oShape.Height = height;

                    oDoc.Save();
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    //关闭word
                    oWord.Quit(Type.Missing, Type.Missing, Type.Missing);
                }

            }
            else
            {
                //关闭word
                oWord.Quit(Type.Missing, Type.Missing, Type.Missing);

                throw new Exception("找不到书签" + oEndOfDoc.ToString());
            }
        }
由于默认的颜色是在是不敢恭维,一片的冷色调加灰色背景,于是增加了一些颜色的调整,但添加颜色的方法相对原始,希望有大神看了之后给出更好的方法。

好吧,总结一下,用这个方法操作word图表,无论是从简便性还是运行速率,都比操作Excel图表更胜一筹,唯一的缺点就是图表的样式相对比较难看,当然这里已经进行了一些处理,相对友好了一些。初次写博客,难免有些疏漏,也希望抛砖引玉,得到高手的指教。本文档及代码欢迎转载,但转载前请标明原始出处!

没有更多推荐了,返回首页