MS word文档结构、COM调用和python

2024-09-28 19:04:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用comptypes调用函数并创建msword文档。作为第一次编写这样的程序,我有一些不明白的地方,我想做的是:

  • 在文档中创建节并将其称为A、B、
  • 在每个部分中创建包含文本的段落。对于sectionA,调用段落a1,a2,a3
  • 在每个小节的每个段落中添加格式,每个段落的格式可能不同

下面是VBA中的一些代码片段,使用VBA是因为使用comptypes的翻译几乎是直接的,而且网上有更多的VBA示例

Set myRange = ActiveDocument.Range(Start:= ...., End:= ...) //start and end can be any thing 
ActiveDocument.Sections.Add Range:=myRange  //Section A
Set newRange = ActiveDocument.Range(Start:= ...., End:= ...) //start and end can be any thing 
newRange.Paragraphs.Add

我被困在选择段落a1和设置它的文本。我缺少的是一个say get collection of paragraphs in section A函数


Tags: and文档文本a1格式rangevbastart
1条回答
网友
1楼 · 发布于 2024-09-28 19:04:26

下面的VBA基于问题中的代码,演示如何获取Document对象、添加Section、获取该SectionParagraphs、获取文档中任何给定SectionParagraphs、从Paragraphs集合获取第一个或任何Paragraph

Set doc = ActiveDocument   //More efficient if the Document object will be used more than once
Set section1 = doc.Sections.Add(Range:=myRange)  //Section A | Type Word.Section
Set section1Paras = section1.Paragraphs  //Type Word.Paragraphs
//OR
Set sectionParas = doc.Sections(n).Paragraphs //where n = section index number
Set para = sectionParas.First //OR =sectionParas(n) where n= paragraph index number

相关问题 更多 >