Python-批处理.xlsx文件与.xls文件相互转换

由于最近在学习自动化生成测试报告,但在通过xlutils实现保留excel原格式情况下追加写入数据时,excel文件若为.xlsx文件会导致脚本无法运行。故需要实现.xlsx文件与.xls文件的相互转换

身为21世纪的程序媛,我们怎么能把.xlsx文件一个一个打开又另存为.xls呢?还不python脚本写起来~
一、.xlsx文件转为.xls文件:
# encoding: utf-8
from ctypes import *
import time
import win32com.client as win32
import os
def transform(parent_path,out_path):
    fileList = os.listdir(parent_path)  #文件夹下面所有的文件
    num = len(fileList)
    for i in range(num):
        file_Name = os.path.splitext(fileList[i])   #文件和格式分开
        if file_Name[1] == '.xlsx':
            transfile1 = parent_path+'\\'+fileList[i]  #要转换的excel
            transfile2 = out_path+'\\'+file_Name[0]    #转换出来excel
            excel=win32.gencache.EnsureDispatch('excel.application')
            pro=excel.Workbooks.Open(transfile1)   #打开要转换的excel
            pro.SaveAs(transfile2+".xls", FileFormat=56)  #另存为xls格式
            pro.Close()
            excel.Application.Quit()

if __name__=='__main__':
    path1=r"E:\untitled1\test_report_demo"  #待转换文件所在目录
    path2=r"E:\untitled1\test_data"  #转换文件存放目录
    transform(path1, path2)
二、.xls文件转为.xlsx文件:
#encoding: utf-8
from ctypes import *
import time
import win32com.client as win32
import os
def transform(parent_path,out_path):
    fileList = os.listdir(parent_path)  #文件夹下面所有的文件
    num = len(fileList)
    for i in range(num):
        file_Name = os.path.splitext(fileList[i])   #文件和格式分开
        if file_Name[1] == '.xls':
            transfile1 = parent_path+'\\'+fileList[i]  #要转换的excel
            transfile2 = out_path+'\\'+file_Name[0]    #转换出来excel
            excel=win32.gencache.EnsureDispatch('excel.application')
            pro=excel.Workbooks.Open(transfile1)   #打开要转换的excel
            pro.SaveAs(transfile2 + ".xlsx", FileFormat=51)  # 另存为xlsx格式
            pro.Close()
            excel.Application.Quit()

if __name__=='__main__':
    path1=r"E:\untitled1\test_report_demo"  #待转换文件所在目录
    path2=r"E:\untitled1\test_data"  #转换文件存放目录
    transform(path1, path2)
在目录前加一个r的原因:

r是保持字符串原始值的意思,就是说不对其中的符号进行转义。因为windows下的目录字符串中通常有斜杠"",而斜杠在Python的字符串中有转义的作用。例如:\n表示换行如果路径中有\new就会被转义。加上r就是为了避免这种情况。

评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值