1、目录下多个xls文件转换
import win32com.client as win32
import os
# 另存为xlsx的文件路径
xlsx_file = r"C:\Users\HP\Desktop\新建文件夹\xlsx"
xls_file = r"C:\Users\HP\Desktop\新建文件夹"
for file in os.scandir(xls_file):
suffix = file.name.split(".")[-1]
if file.is_dir():
pass
else:
if suffix == "xls":
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(file.path)
# xlsx文件夹路径\\文件名x
wb.SaveAs(xlsx_file +"\\"+ file.name + "x", FileFormat=51)
wb.Close()
excel.Application.Quit()
2、增加界面化组件,让用户自行选择文件夹
import os
import win32com.client as win32
import easygui as eg
def pick_package():
# 打开windows窗口,选择一个文件夹,并返回文件夹路径
return eg.diropenbox()
if __name__ == "__main__":
package = pick_package() # 返回文件夹路径
xlsx_file = package + "\\xlsx"
for file in os.scandir(package):
# 获取后缀
suffix = file.name.split(".")[-1]
if file.is_dir(): # 忽略文件夹
pass
else:
if suffix == "xls":
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(file.path)
wb.SaveAs(xlsx_file + "\\" + file.name + "x", FileFormat=51)
wb.Close()
excel.Application.Quit()
自动创建文件夹
import os
import win32com.client as win32
import easygui as eg
def pick_package():
# 打开windows窗口,选择一个文件夹,并返回文件夹路径
return eg.diropenbox()
if __name__ == "__main__":
package = pick_package() # 返回文件夹路径
# 在当前文件夹下创建xlsx文件夹,用于存放转换的文件
if not os.path.exists(package+"\\" + "xlsx"):
os.mkdir(package+"\\" + "xlsx")
xlsx_file = package+"\\" + "xlsx"
print(xlsx_file)
for file in os.scandir(package):
# 获取后缀
suffix = file.name.split(".")[-1]
if file.is_dir(): # 忽略文件夹
pass
else:
if suffix == "xls":
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(file.path)
wb.SaveAs(xlsx_file + "\\" + file.name + "x", FileFormat=51)
wb.Close()
excel.Application.Quit()
xlsx转xls
import os
import win32com.client as win32
import easygui as eg
def pick_package():
# 打开windows窗口,选择一个文件夹,并返回文件夹路径
return eg.diropenbox()
if __name__ == "__main__":
package = pick_package() # 返回文件夹路径
# 在当前文件夹下创建xls文件夹,用于存放转换的文件
if not os.path.exists(package+"\\" + "xls"):
os.mkdir(package+"\\" + "xls")
xlsx_file = package+"\\" + "xls"
for file in os.scandir(package):
# 获取后缀
suffix = file.name.split(".")[-1]
# 如果后缀为xlsx,执行xlsx转xls
if suffix == "xlsx":
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(file.path)
name = file.name.split(".")[0]
wb.SaveAs(xlsx_file + "\\" + name, FileFormat=56)
wb.Close()
excel.Application.Quit()
SaveAs另存为xlsx时需补后缀x,另存为xls时仅路径和文件名即可