从Word文档中修改Excel Chart的内容

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using log4net;
using Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "ConsoleApplication2.exe.config", Watch = true)]
namespace ConsoleApplication2
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            ILog log = log4net.LogManager.GetLogger(typeof(Program));
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = false;
            ofd.Filter = "Word Document|*.docx;*.doc";
            ofd.ShowDialog();
            string DocPath = ofd.FileName;
            log.Info("Open the file : " + DocPath);
            try
            {
                Word.Application wdApplication = new Word.Application();
                wdApplication.Visible = true;
                Word.Document wdDoc = wdApplication.Documents.Open(DocPath);
                foreach (Word.InlineShape wdInlineShape in wdDoc.InlineShapes)
                {
                    if (wdInlineShape.OLEFormat.ProgID.Equals("Excel.Sheet.8"))
                    {
// 下一步很重要,否则会报“对象没有连接到服务器 
// (Exception from HRESULT: 0x800401FD (CO_E_OBJNOTCONNECTED))”异常。
                        wdInlineShape.OLEFormat.Open();
                        Excel.Workbook xlWorkbook = wdInlineShape.OLEFormat
                            .Object;

                        if (xlWorkbook != null)
                        {
                            xlWorkbook.ActiveChart.HasTitle = true;
                            xlWorkbook.ActiveChart.ChartTitle.Text = "Test";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Fatal(string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
            log.Error("Finished");
            Console.ReadKey();
        }
    }
}

欢迎访问《许阳的红泥屋

posted @ 2012-07-05 14:35  许阳 无锡  阅读(481)  评论(0编辑  收藏  举报