python批量转换word和excel格式

python批量转换word和excel格式

实现的目标

批量将目录(包括子目录)下的所有doc和xls文件,转换为docx和xlsx格式。

用到的python模块

pip install pywin32

脚本内容

import os
import os.path
import win32com.client as win32
import threading
#解决pywintypes.com_error报错
import pythoncom

## 根目录
rootdir = u'D:\旧版文档'

def xls2xlsx():
    #解决pywintypes.com_error报错
    pythoncom.CoInitialize()
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    #遍历文档目录中的所有xls文件
    for parent, dirnames, filenames in os.walk(rootdir):
        for fn in filenames:
            filedir = os.path.join(parent, fn)
            if fn.endswith('.xls'):
                #打印处理的文件名
                print(filedir)
                try:
                    #打开xls文件
                    wb = excel.Workbooks.Open(filedir)
            # xlsx: FileFormat=51
            # xls:  FileFormat=56,
                    try:
                        #保存为xlsx文件,51表示xslx文件格式
                        wb.SaveAs(filedir.replace('xls', 'xlsx'), FileFormat=51)
                        wb.Close()
                        #删除xls文件
                        os.remove(filedir)
                    except Exception as e:
                        print(e)
                except Exception as e:
                    print(e)
    excel.Application.Quit()
    print('xls end')

def doc2docx():
    pythoncom.CoInitialize()
    word = win32.Dispatch("Word.Application")
    # 三个参数:父目录;所有文件夹名(不含路径);所有文件名
    #获取所有doc文件
    for parent, dirnames, filenames in os.walk(rootdir):
        for fn in filenames:
            filedir = os.path.join(parent, fn)
            if fn.endswith('.doc'):
                #打印处理的文件名
                print(filedir)
                try:
                    #打开所有doc文件
                    doc = word.Documents.Open(filedir)
                    try:
                        #另存为后缀为".docx"的文件,其中参数12指docx文件
                        doc.SaveAs("{}x".format(filedir),12)
                        doc.Close()
                        #删除doc文件
                        os.remove(filedir)
                    except Exception as e:
                        print(e)
                except Exception as e:
                    print(e)
    word.Quit()
    print('doc end')

def main():
    #启用多线程xls和doc文件分别另存为
    threads = []
    t1 = threading.Thread(target=xls2xlsx,args=())
    t2 = threading.Thread(target=doc2docx,args=())
    threads.append(t1)
    threads.append(t2)
    for t in threads:
        t.setDaemon(True)
        t.start()
    for i in threads:
        i.join()
    print("所有任务完成")
        
if __name__ == '__main__':
    main()

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值