我正在和Microsoft.Office.Interop.Word.Application一起工作。我有一些模板化的Word文档,其中文件中将有一些令牌,如PutfirstTableHere在运行时,我将创建表格,并想要的,以取代现有的word文档中的令牌生成的表格,任何机构可以让我知道,我可以替换一个字符串令牌在word中的表格?找不到我当前问题的任何示例/样本
发布于 2013-07-30 20:25:58
试试这个:
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命名空间的文档类型;
发布于 2013-07-31 05:52:58
您可以使用Find Interface及其Execute方法搜索文档内容。第一个参数是要在创建find对象的范围内搜索的文本(在本例中,我建议使用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);
}create table方法示例:
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);
}
}https://stackoverflow.com/questions/17946690
复制相似问题