使用Python更新MS Word(或Open Office)书签

0 投票
2 回答
2858 浏览
提问于 2025-04-15 15:39

我想用一个Python脚本来填充MSWord中的书签。
我在win32com(MSWord)或者PyUno(OpenOffice)里找不到这样的功能。

有没有人知道怎么在Python中使用书签?

2 个回答

0

看看这个例子,可能对你的问题有帮助:

def addText(self, bookmark):
    self.wordApp.ActiveDocument.Bookmarks(bookmark).Select()
    self.wordApp.Selection.TypeText(self.some_text)

# from pandas data frame into word table 
def addTable(self, bookmark, df):
    self.wordApp.ActiveDocument.Bookmarks(bookmark).Select()
     table = location.Tables.Add(location, len(df) + 1, len(df.columns), 1, 1)
    table.AutoFormat(40)
    for i, item in enumerate(df):
        table.Cell(1, i + 1).Range.InsertAfter(item)
        table.Cell(1, i + 1).Range.ParagraphFormat.Alignment = 1
    sel.SelectRow()
    sel.BoldRun()
    table.Rows(1).HeadingFormat = True
    for c in range(2, len(df) + 2):
        for r in range(1, len(df.columns) + 1):
            table.Cell(c, r).Range.ParagraphFormat.Alignment = 1
            if pd.isnull(df.ix[c - 2][r - 1]):
                continue
            table.Cell(c, r).Range.InsertAfter(df.ix[c - 2, r - 1])
1

你在win32com里找不到那些函数,而是要去查你正在使用的COM对象的文档。在这个例子中,就是Word.Application。

你可以查看一些示例Python代码,它使用这个COM对象来创建书签

最新的Word对象模型参考可以在MSDN找到

撰写回答