赞
踩
import win32com.client
import os
def xlsx_to_xls(fname, export_name, delete_flag=True):
“”"
将xlsx文件转化为xls文件
:param fname: 传入待转换的文件路径(可传绝对路径,也可传入相对路径,都可以)
:param export_name: 传入转换后到哪个目录下的路径(可传绝对路径,也可传入相对路径,都可以)
:param delete_flag: 转换成功后,是否删除原来的xlsx的文件,默认删除 布尔类型
:return: 无返回值
“”"
excel = win32com.client.DispatchEx(‘Excel.Application’)
excel.Visible = False
excel.DisplayAlerts = False
absolute_path = os.path.join(os.path.dirname(os.path.abspath(fname)), os.path.basename(fname))
save_path = os.path.join(os.path.dirname(os.path.abspath(export_name)), os.path.basename(export_name))
wb = excel.Workbooks.Open(absolute_path)
wb.SaveAs(save_path, FileFormat=56) # FileFormat = 51 is for .xlsx extension
wb.Close() # FileFormat = 56 is for .xls extension
excel.Application.Quit()
if delete_flag:
os.remove(absolute_path)
def xls_to_xlsx(fname, export_name, delete_flag=True):
“”"
将xlsx文件转化为xls文件
:param fname: 传入待转换的文件路径(可传绝对路径,也可传入相对路径,都可以)
:param export_name: 传入转换后到哪个目录下的路径(可传绝对路径,也可传入相对路径,都可以)
:param delete_flag: 转换成功后,是否删除原来的xlsx的文件,默认删除 布尔类型
:return: 无返回值
“”"
excel = win32com.client.DispatchEx(‘Excel.Application’)
excel.Visible = False
excel.DisplayAlerts = False
absolute_path = os.path.join(os.path.dirname(os.path.abspath(fname)), os.path.basename(fname))
save_path = os.path.join(os.path.dirname(os.path.abspath(export_name)), os.path.basename(export_name))
# os.path.join(export_name,os.path.basename(fname).split('.xls')[0])
wb = excel.Workbooks.Open(absolute_path)
wb.SaveAs(save_path, FileFormat=51) # FileFormat = 51 is for .xlsx extension
print(wb.name)
wb.Close() # FileFormat = 56 is for .xls extension
excel.Application.Quit()
if delete_flag:
os.remove(absolute_path)
rootdir = r"D:\BS\test1"
name_list=os.listdir(rootdir)
print(name_list)
new_path=r’D:\BS\test2’
cnt=0
for name in name_list:
path=os.path.join(rootdir, name)
cnt+=1
# xls_to_xlsx(path,new_path+‘\’+str(name.split(‘.xls’)[0])+‘_’+str(cnt),False)
xls_to_xlsx(path, new_path + ‘\’ + str(name.split(‘.’)[0]), False)
print(‘本次共修改xls:’+str(cnt)+‘个’)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。