Python 3 Office document format conversion

As mentioned last time, there is a prerequisite for quickly extracting pictures from word and excel files, that is, the extension of the target file must be .docx\.xlsx . This time we use Python 3 to realize automatic conversion of .doc\.xls files to .docx\.xlsx.



Python 3 implementation code






import win32com.client as win32  # 引入win32com库(win32com功能强大,可以操作word、调用宏等等等)import os                        # 引入os库(文件及目录操作)
#自定义xls转xlsx功能函数def xls_xlsx(fname):    excel = win32.gencache.EnsureDispatch('Excel.Application')    xls = excel.Workbooks.Open(fname)       # 目标路径下的文件    xls.SaveAs(fname+'x', FileFormat = 51)    #51为xlsx 56为xls    xls.Close()                             #关闭资源    excel.Application.Quit()                #退出Excel    os.remove(fname)                        #删除原Excel文件 #自定义doc转docx功能函数def doc_docx(fname):    word = win32.Dispatch('Word.Application')    doc = word.Documents.Open(fname)  # 目标路径下的文件    doc.SaveAs(fname+'x'16)  # 16为xlsx文件格式    doc.Close()                 #关闭资源    word.Quit()                 #退出word    os.remove(fname)           #删除原Word文件
if __name__=="__main__":        #主程序入口    xls_xlsx('xx\xx\xx.xls')    #调用xlsx转换函数    doc_docx('xx\xx\xx.doc')    #调用docx转换函

The above is the Pyhton 3 source code of the function implementation. Interested friends can try it by themselves.


Guess you like

Origin blog.51cto.com/15069490/2578659