自动批量一次性转换工具,doc转docx,xls转xlsx,ppt转pptx,基于python
【代码】自动批量一次性转换工具,doc转docx,xls转xlsx,ppt转pptx,基于python。
·
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 15:19:24 2020
需要先安装office或者wps,自动将py文件同级文件夹下(含子文件夹)内所有的doc、xls、ppt转成docx/xlsx/pptx
已经是纯py程序,直接在python环境下运行即可,转换完成后会自动删除老版本文件。自己根据需要可调整。doc和xls文件转换时属于静默转换,ppt因为office软件原因,不支持后台静默转换,会跳出ppt软件窗口,但转换完成后会自动关闭。
原理:直接调用office相关API执行打开文件、另存为等操作,因为WPS的API兼容OFFICE,所以安装了WPS后也可以用。
@author: w
"""
import os
import logging
from win32com import client
logging.basicConfig(filename='rz.txt',level=logging.DEBUG,format='%(asctime)s-%(levelname)s-%(message)s')#启动日志
logging.debug("程序开始!")
def doc_to_docx(path):
if os.path.splitext(path)[1] == ".doc":
word = client.Dispatch('Word.Application')
doc = word.Documents.Open(path) # 目标路径下的文件
doc.SaveAs(os.path.splitext(path)[0]+".docx", 16) # 转化后路径下的文件
doc.Close()
word.Quit()
def xls_to_xlsx(path):
if os.path.splitext(path)[1] == ".xls":
excel = client.Dispatch('Excel.Application')
xls = excel.Workbooks.Open(path) # 目标路径下的文件
xls.SaveAs(os.path.splitext(path)[0]+".xlsx", 51) # 转化后路径下的文件
xls.Close()
excel.Quit()
def ppt_to_pptx(path):
if os.path.splitext(path)[1] == ".ppt":
powerpoint = client.Dispatch('PowerPoint.Application')
client.gencache.EnsureDispatch('PowerPoint.Application')
powerpoint.Visible=1
ppt = powerpoint.Presentations.Open(path) # 目标路径下的文件
ppt.SaveAs(os.path.splitext(path)[0]+".pptx") # 转化后路径下的文件
ppt.Close()
powerpoint.Quit()
def find_file(path, ext, file_list=[]):
dir = os.listdir(path)
for i in dir:
i = os.path.join(path, i)
if os.path.isdir(i):
find_file(i, ext, file_list)
else:
if ext == os.path.splitext(i)[1]:
file_list.append(i)
return file_list
#获取当前py文件所在路径
dir_path=os.path.split(os.path.realpath(__file__))[0]
#print(dir_path)
#os._exit()
#dir_path = "D:\我的文档\桌面\附件1文件"#批量转换文件夹
ext = ".doc"
file_list = find_file(dir_path, ext)
for file in file_list:
try:
doc_to_docx(file)
logging.debug(file)
os.remove(file)
except Exception as bcnr:
logging.debug("可接受异常:%s(一般是磁盘缓存未能及时更新导致)" % bcnr)
#print(file_list)
ext = ".xls"
file_list = find_file(dir_path, ext)
for file in file_list:
try:
xls_to_xlsx(file)
logging.debug(file)
os.remove(file)
except Exception as bcnr:
logging.debug("可接受异常:%s(一般是磁盘缓存未能及时更新导致)" % bcnr)
#print(file_list)
ext = ".ppt"
file_list = find_file(dir_path, ext)
for file in file_list:
try:
ppt_to_pptx(file)
logging.debug(file)
os.remove(file)
except Exception as bcnr:
logging.debug("可接受异常:%s(一般是磁盘缓存未能及时更新导致)" % bcnr)
#print(file_list)
更多推荐


所有评论(0)