使用VSTO阅读和修改Word doc的文本

时间:2014-10-15 08:38:45

标签: c# .net ms-word vsto

我正在写一个MS Word插件。仍处于学习VSTO的最初阶段。所以基本上到目前为止我在Word文档中所拥有的是一些用户书面文本(一个完整的Word文档),其形式有点如下:

Hello, my name is <%NAME%>. I am <%AGE%> years old and i live in <%COUNTRY%>.

那些&lt; %%&gt;是用户从自定义任务窗格拖放的变量。

我要做的是用从某些数据文件读取的一些实际数据值替换这些变量。但是现在我正在寻找的是一种方法来读取字符串中当前活动文档的内容,然后用虚拟数据值替换那些变量,然后用这个新的文档替换旧文档,替换实际值取而代之的是NAME,AGE等。最好在onSaveAs事件中,但由于不可用,所以我必须在BeforeSave事件中进行。

总之,我正在寻找的是一种方式:

  • 阅读当前文档的内容。
  • 修改这些内容。
  • 写回来。

我已经在网上和MSDN上搜索了好几个小时了,但实际上找不到任何有用的东西,或者可能无法实现它,因为我是新手。

我读到的一些文章是:

add-in in VSTO - How to get text from Word document using Ribbon with button

How To Read & Write Text From Word Document Using VSTO In C#

Globals.ThisAddIn.Application.Selection.Text;

这仅提供所选文本,但我需要所选文档的所有文本和未选中的文本。

我的ThisAddin.cs中的当前代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Word;


namespace dragdrop
{
    public partial class ThisAddIn
    {

        private void ThisAddIn_Startup(object sender, System.EventArgs e){Globals.ThisAddIn.CustomTaskPanes.Add(new OrdersListUserControl(), "Drag and Drop List Items on Word Doc").Visible = true;}       
        private void ThisAddIn_Shutdown(object sender, System.EventArgs e){}
        public void OnDropOccurred(object data) //adding dropped text on current cursor position.
        {
            Word.Selection currentSelection = Application.Selection;
            currentSelection.TypeText(data.ToString());
        }
        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);

        }


        #endregion
    }
}

任何形式的帮助/指示都非常受欢迎。感谢。

编辑:我设法使用以下内容获取内容:

Globals.ThisAddIn.Application.ActiveDocument.Range(0, 5).Text

但问题是,如果结束范围超过文档的总长度,它将崩溃!那么如何获取文档的长度以便将其作为第二个参数提供,或者有更好的方法吗?另外我想知道只是阅读文本并将其写回会使文本失去它的格式和样式所以有没有办法保留我想要实现的目标?非常感谢您清除所有这些混淆。

1 个答案:

答案 0 :(得分:4)

使用文档的Content属性获取文档范围的第一个和最后一个索引

Microsoft.Office.Interop.Word._Document oDoc = 
     Globals.ThisAddIn.Application.ActiveDocument;
Object start = oDoc.Content.Start;
Object end = oDoc.Content.End;

// select entire document 
oDoc.Range(ref start,ref end).Select();
相关问题