【问题标题】:Reading/Writing MS Word files in Python在 Python 中读/写 MS Word 文件
【发布时间】:2010-09-16 08:24:32
【问题描述】:

是否可以在不使用 COM 对象的情况下在 Python 中读取和写入 Word(2003 和 2007)文件?
我知道我可以:

f = open('c:\file.doc', "w")
f.write(text)
f.close()

但 Word 会将其读取为 HTML 文件而不是本机 .doc 文件。

【问题讨论】:

    标签: python ms-word read-write


    【解决方案1】:

    doc(本例中为 Word 2003)和 docx(Word 2007)是不同的格式,后者通常只是 xml 和图像文件的存档。我想通过操作这些 xml 文件的内容来写入 docx 文件是很有可能的。但是,我看不出没有某种类型的 COM 组件接口如何读取和写入 doc 文件。

    【讨论】:

      【解决方案2】:

      我会研究 IronPython,它本质上可以访问 windows/office API,因为它在 .NET 运行时上运行。

      【讨论】:

        【解决方案3】:

        python-docx,其官方文档在here

        这对我来说效果很好。

        【讨论】:

        • 但它支持 .doc 格式,我试过但它给我一个 ValueError ValueError: file '<open file 'file.doc', mode 'r' at 0x7f29a1b5a6f0>' is not a Word file, content type is 'application/vnd.openxmlformats-officedocument.themeManager+xml
        • 它被称为 python-docx 而不是 python-doc,所以没有。 :)
        • @Damian 但问题也与 .doc 文件有关,因此您应该注意您的答案仅适用于 .docx 文件。
        • 对打开 .doc 文件有什么想法吗?
        【解决方案4】:

        如果你只是看什么,那就simplest使用linux soffice命令将其转换为文本,然后将文本加载到python中:

        【讨论】:

        • +1 我不知道为什么这会得到反对票。这有时是唯一的解决方案,有时就足够了。
        猜你喜欢
        • 2010-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-02
        • 2019-03-10
        • 1970-01-01
        相关资源
        最近更新 更多