用Word表替换Word文档中的字符串标记

时间:2013-07-30 12:11:39

标签: .net ms-word range office-interop

我正在使用Microsoft.Office.Interop.Word.Application。我有一些模板化的word文档,其中的文件会有一些令牌 [PutfirstTableHere] 在运行时,我将创建表,并希望用生成的表替换现有word文档中的该标记 任何正文都可以让我知道如何用Word中的表替换字符串标记? 无法找到我当前问题的任何示例/示例

2 个答案:

答案 0 :(得分:0)

试试这个:

protected void InsertTableAtBookMark(string[][] docEnds, string bookmarkName)
    {
        Object oBookMarkName = bookmarkName;
        Range wRng = WordDoc.Bookmarks.get_Item(ref oBookMarkName).Range;

        Table wTable = WordDoc.Tables.Add(wRng, docEnds.Length, docEnds[0].Length);
        wTable.set_Style("Table Grid");

        for (int i = 0; i < docEnds.Length; i++)
        {
            for (int j = 0; j < docEnds[0].Length; j++)
            {
                wTable.Cell(i, j).Range.Text = docEnds[i][j];
                wTable.Cell(1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                wTable.Cell(1, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            }
        }
        Borders wb = wTable.Borders;
        wb[WdBorderType.wdBorderHorizontal].LineStyle = WdLineStyle.wdLineStyleNone;
        wb[WdBorderType.wdBorderVertical].LineStyle = WdLineStyle.wdLineStyleNone;

        wTable.Borders = wb;
    }

其中WordDoc的类型为来自Microsoft.Office.Interop.Word命名空间的Document;

答案 1 :(得分:0)

您可以使用Find Interface及其Execute方法搜索文档内容。第一个参数是在范围内搜索的文本(在您的情况下,我建议使用Word.Document.Content属性),从中创建查找对象。

代码:

Word.Document doc = Application.ActiveDocument;
Word.Range wholeDoc = doc.Content;                

Word.Find find = wholeDoc.Find;

object token = "[MyTableToken]";                
object missing = Type.Missing;

bool result = find.Execute(ref token, true, true, ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

while (result)
{
    // wholeDoc object is replaced with executed search/find result
    CreateTable(wholeDoc.Duplicate);

    result = find.Execute(ref token, true, true, ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
}

示例创建表方法:

private void CreateTable(Word.Range range)
{
    Word.Tables tables = null;
    try
    {
        int sampleRowNumber = 3, sampleColumnNumber = 3;

        range.Text = "";
        tables = range.Tables;

        tables.Add(range, sampleRowNumber, sampleColumnNumber);
    }
    finally
    {
        Marshal.ReleaseComObject(range);
        Marshal.ReleaseComObject(tables);
    }
}