如何使用Python将docx转换为doc?

2024-09-30 14:38:18 发布

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

如何使用Python将file.docx转换为file.doc?我有一个以docx格式输出文件的代码,但这个程序是为只能使用word2003的人编写的,所以我需要使用Python将该文件转换为.doc。我怎么做?先谢谢你


Tags: 文件代码程序doc格式filedocxword2003
2条回答

有点笨重,但您可以使用pywinauto以编程方式在word中打开.docx文档,然后另存为.doc。它将使用word进行转换,因此它应该尽可能干净

这是我用来在word中转换为pdf的代码片段(这只是一个测试)。您必须按照保存为.doc所需的按键操作

import pywinauto
from pywinauto.application import Application


app1 = Application(backend="uia").connect(path="C:\\Program Files (x86)\\Microsoft Office\\root\\Office16\\WINWORD.EXE")
wordhndl = app1.top_window()


wordhndl.type_keys('^o')
wordhndl.type_keys('%f')
wordhndl.type_keys('^o')
wordhndl.type_keys('^o')

#Now that we're in a sub-window, using the top_window() handle doesn't work...
#Instead refer to absolute (using friendly_class_name())
app1.Dialog.Open.type_keys("Y:\\996.Software\\04.Python\\Test\\SampleDoc1.docx")
app1.Dialog.Open.type_keys('~')


#Publish it to pdf
app1.SampleDoc1docx.type_keys('%f')
app1.SampleDoc1docx.type_keys('e')
app1.SampleDoc1docx.type_keys('p')
app1.SampleDoc1docx.type_keys('a')
app1.SampleDoc1docx.PublishasPDForXPS.Publish.type_keys('~')


#Deal with popups & prompts
if app1.Dialog.PublishasPDForXPS.ConfirmSaveAs.exists():
    app1.Dialog.PublishasPDForXPS.ConfirmSaveAs.Yes.click()  #This line can take some time...

我认为.doc击键是(未经测试的)

app1.SampleDoc1docx.type_keys('%f')
app1.SampleDoc1docx.type_keys('a')
app1.SampleDoc1docx.type_keys('y')
app1.SampleDoc1docx.type_keys('4')
app1.SampleDoc1docx.type_keys('{DOWN}')
app1.SampleDoc1docx.type_keys('{DOWN}')
app1.SampleDoc1docx.type_keys('~')
app1.SampleDoc1docx.type_keys('{RIGHT}')
app1.SampleDoc1docx.type_keys('~')

但是。。。更好的解决办法是使用单词。我以前在word中使用VBA做过这件事。手头没有代码,但一个好的指针应该是: https://www.datanumen.com/blogs/3-quick-ways-to-batch-convert-word-doc-to-docx-files-and-vice-versa/

您可以执行以下操作:

import docx

doc = docx.Document("myWordxFile.docx")
doc.save('myNewWordFile.doc')

也请勾选this。祝你好运

相关问题 更多 >