首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用word加载项在当前位置添加表

使用word加载项在当前位置添加表
EN

Stack Overflow用户
提问于 2019-01-16 04:18:55
回答 1查看 79关注 0票数 1

我想用我的Word外接程序添加一个表,其中包含数据库中的数据。我已经成功地做到了,但现在我对桌子的位置有了问题。我想把它放在Word文档中我当前所在的位置。但是它总是在开始的时候加进去。谁知道如何调整我的起始值始终是我的当前位置的范围?这是我的代码的一部分:

代码语言:javascript
复制
private void createTable_Click(object sender, EventArgs e) {
object start = 0, end = 0;
Word.Document document = Globals.ThisAddIn.Application.ActiveDocument; 
Word.Range rng = document.Range(ref start, ref end);

// Insert a title for the table and paragraph marks.
rng.InsertBefore("List"); 
rng.Font.Name = "Verdana"; 
rng.Font.Size = 16; 
rng.InsertParagraphAfter(); 
rng.InsertParagraphAfter(); 
rng.SetRange(rng.End, rng.End);

// Add the table.
rng.Tables.Add(document.Paragraphs[2].Range, 1, 7, ref missing, ref missing);

// Format the table and apply a style.
Word.Table tbl = document.Tables[1]; tbl.Range.Font.Size = 8;   
tbl.Borders[WdBorderType.wdBorderLeft].LineStyle =
  WdLineStyle.wdLineStyleSingle; 
tbl.Borders[WdBorderType.wdBorderRight].LineStyle =
  WdLineStyle.wdLineStyleSingle; 
tbl.Borders[WdBorderType.wdBorderTop].LineStyle =
  WdLineStyle.wdLineStyleSingle; 
tbl.Borders[WdBorderType.wdBorderBottom].LineStyle =
  WdLineStyle.wdLineStyleSingle; 
tbl.Borders[WdBorderType.wdBorderHorizontal].LineStyle =
  WdLineStyle.wdLineStyleSingle; 
tbl.Borders[WdBorderType.wdBorderVertical].LineStyle =
  WdLineStyle.wdLineStyleSingle;
tbl.Borders[WdBorderType.wdBorderBottom].Color = WdColor.wdColorBlack; tbl.Rows.Alignment = WdRowAlignment.wdAlignRowCenter; tbl.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitWindow);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-16 05:37:22

再读一遍...在当前位置插入-如果您指的是光标所在的位置:

代码语言:javascript
复制
Word.Range rngSel = wdApp.Selection.Range;
rngSel.Tables.Add(//params here);

否则,如果您的意思是在代码插入的信息的末尾,而不是这两行

代码语言:javascript
复制
rng.InsertBefore("List"); 
rng.Font.Name = "Verdana"; 
rng.Font.Size = 16; 
rng.InsertParagraphAfter(); 
rng.InsertParagraphAfter(); 
rng.SetRange(rng.End, rng.End);

使用

代码语言:javascript
复制
rng.Text = "List\n\n"
rng.Font.Name = "Verdana"; 
rng.Font.Size = 16; 
rng.Collapse(WdCollapseDirection.wdCollapseEnd);

\n插入一个新段落(回车符),并且可以作为字符串的一部分包括在内。

将文本直接分配给Range并使用Collapse方法(在我看来)比各种Insert方法更可预测一些。一些Insert方法包括范围中插入的内容,其他方法则不包括。

当不清楚问题可能是什么时,将rng.Select();放在代码中的关键点并注释掉其余行,这样代码就会以可见的范围结束。这通常是关于某个范围问题的根源的信息。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54206253

复制
相关文章

相似问题

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