0

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

4

2 回答 2

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 类型;

于 2013-07-30T12:25:58.363 回答
0

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

代码:

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);
    }
}
于 2013-07-30T21:52:58.200 回答