1

在过去的几天里,我一直在尝试通过其 .xml 文件来操作 MS Word 文档。主要思想是使用 Python 将书签控件插入到现有文档中。我知道有一个名为 Docx 的库已经为 MS Word 提供了一些功能,但它不能满足我的需要(至少现在还没有),所以我正在使用 lxml 库。这是在 word xml 文件中表示书签的方式:

<w:p>
  <w:r>
    <w:t xml:space="preserve">This is text with a </w:t>
  </w:r>
  <w:bookmarkStart w:id="0" w:name="myAnchor"/>
  <w:r>
    <w:t>bookmark</w:t>
  </w:r>
  <w:bookmarkEnd w:id="0"/>
</w:p>

在其他帖子中进行了一些研究后,我有以下代码:

def getXml(docxFilename):
    zip = zipfile.ZipFile(open(docxFilename, "rb"))
    xmlString = zip.read("word/document.xml")
    return xmlString

#Importa a string o
tmp_doc_xml = getXml("/home/davids/Documents/tmp_doc.docx")
root = etree.fromstring(tmp_doc_xml)
a = open("/home/davids/PycharmProjects/Bookmarks/root_xml", "w")

print >>a, (etree.tostring(root, pretty_print=True))

bookmarks_list = root.findall('.//' + qn('w:bookmarkStart'))
for bookmark in bookmarks_list:
    name = bookmark.get(qn('w:name'))
    print >>a, 'bookmark: '+ str(bookmark) + '\n' + 'content: ' + (etree.tostring(bookmark, pretty_print=True))

bookmarks_list = root.findall('.//' + qn('w:bookmarkEnd'))
for bookmark in bookmarks_list:
    name = bookmark.get(qn('w:name'))
    print >>a, 'bookmark: '+ str(bookmark) + '\n' + 'content: ' + (etree.tostring(bookmark, pretty_print=True))

我想强调一下,这段代码的一些内容不是我创建的,而是我在互联网上找到的函数的汇编。

基本上,它解压缩 word 文件并将其 document.xml 文件保存为字符串,然后将该字符串作为树格式导入。所以,我想做的是:

一个。将新书签插入现有 xml 代码

湾。显示书签中的内容(即相同id号的bookmarkStart和bookmarkEnd之间的内容)

谢谢,大卫

4

0 回答 0