Microsoft Word 编程

来自百合仙子's Wiki
跳转到导航 跳转到搜索

本文以 Python 语言说明一些常用的操作。需要导入的模块如下:

import win32com
from win32com.client import Dispatch, constants

本文中,示例代码中的同名变量指向同样的对象,除非是较完整的代码片断。

程序

打开,可以使用已有的程序实例:

w = win32com.client.Dispatch('Word.Application')
# 或者
w = win32com.client.gencache.EnsureDispatch('Word.Application')

总是打开新的程序实例:[1]

w = win32com.client.DispatchEx('Word.Application')

属性:

Visible
窗体是否可见(0 或 1)
Documents

方法:

Quit
退出

文档对象

文件操作

新建文档

doc = w.Documents.Add()

打开文档

doc = w.Documents.Open(FileName=filenamein)

文档是否已保存所有的修改

doc.Saved

保存文档[1][2][3]

doc.Save() #保存到原文档
doc.SaveAs('a.doc')

保存为 PDF[4]

wdFormatPDF = 17
doc.SaveAs('a.pdf', FileFormat=wdFormatPDF)

关闭文档

doc.Close()
# 不保存直接关闭(wdDoNotSaveChanges、wdPromptToSaveChanges 或 wdSaveChanges)
doc.Close(0)

属性

Paragraphs
段落对象

排版对象

段落对象

p.Alignment

取得或设置对齐方式,其值是一个 WdParagraphAlignment 枚举[5]

wdAlignParagraphLeft
Left-aligned
wdAlignParagraphCenter
Center-aligned
wdAlignParagraphRight
Right-aligned
wdAlignParagraphJustify
Fully justified
wdAlignParagraphDistribute
Paragraph characters are distributed to fill the entire width of the paragraph
wdAlignParagraphJustifyMed
Justified with a medium character compression ratio
wdAlignParagraphJustifyHi
Justified with a high character compression ratio
wdAlignParagraphJustifyLow
Justified with a low character compression ratio
wdAlignParagraphThaiJustify
Justified according to Thai formatting layout
Range
Range对象
TabStops
Tabstop对象集合

注意

  1. 段落的 Range.Text 会以 \r 结尾。
  2. 段落的 Range.Text 被修改后,如果新文本仍以 \r 结尾,则当前对象会自动移到下一个段落;否则与下一个段落合并

Range对象

属性:

Start
End
Text
文本字符串
Font
字体对象

方法:

InsertBefore
在 Range 前插入文本
InsertAfter

字体对象

属性:

Bold
Italic
Name
字体名,可写。如果有更详细的设定,此值为空
NameAscii
ASCII 字符字体名
NameOther
128-255 部分字符字体名
NameFarEast
东亚字符字体名
Size

方法:

Shrink, Grow
增大/减小字号

Tabstop对象

Leader
前导字符, WdTabLeader 枚举类型[6]
wdTabLeaderSpaces
Spaces. default
wdTabLeaderDots
Dots. 此样式可用于目录
wdTabLeaderDashes
Dashes
wdTabLeaderLines
Double lines
wdTabLeaderHeavy
A heavy line
wdTabLeaderMiddleDot
A middle dot

参见

外部链接

参考资料