首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Word表格替换word文档中的字符串标记

问用Word表格替换word文档中的字符串标记
EN

Stack Overflow用户
提问于 2013-07-30 20:11:39
回答 2查看 1.1K关注 0票数 0

我正在和Microsoft.Office.Interop.Word.Application一起工作。我有一些模板化的Word文档,其中文件中将有一些令牌,如PutfirstTableHere在运行时,我将创建表格,并想要的,以取代现有的word文档中的令牌生成的表格,任何机构可以让我知道,我可以替换一个字符串令牌在word中的表格?找不到我当前问题的任何示例/样本

EN

回答 2

Stack Overflow用户

发布于 2013-07-30 20:25:58

试试这个:

代码语言:javascript
复制
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命名空间的文档类型;

票数 0
EN

Stack Overflow用户

发布于 2013-07-31 05:52:58

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

代码:

代码语言:javascript
复制
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);
}

create table方法示例:

代码语言:javascript
复制
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);
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17946690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档