Excel:.xlsx和.xls互转(Python)

.xlsx——>.xls

# encoding: utf-8
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':
            tranfile1=parent_path+'\\'+fileList[i]  #要转换的excel
            tranfile2=out_path+'\\'+file_Name[0]    #转换出来excel
            excel=win32.gencache.EnsureDispatch('excel.application')
            pro=excel.Workbooks.Open(tranfile1)   #打开要转换的excel
            pro.SaveAs(tranfile2+".xls",FileFormat=56)  #另存为xls格式
            pro.Close()
            excel.Application.Quit()
if __name__=='__main__':
    root1=r"D:\test\da"  #待转换文件所在目录
    root2=r"D:\test\xiao"  #转换文件存放目录
    transform(root1,root2)

.xls——…xlsx

# encoding: utf-8
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':
            tranfile1=parent_path+'\\'+fileList[i]  #要转换的excel
            tranfile2=out_path+'\\'+file_Name[0]    #转换出来excel
            excel=win32.gencache.EnsureDispatch('excel.application')
            pro=excel.Workbooks.Open(tranfile1)   #打开要转换的excel
            pro.SaveAs(tranfile2+".xlsx",FileFormat=51)  #另存为xls格式
            pro.Close()
            excel.Application.Quit()
if __name__=='__main__':
    root1=r"D:\test\xiao"  #待转换文件所在目录
    root2=r"D:\test\da"  #转换文件存放目录
    transform(root1,root2)

二者的区别主要就是这句:pro.SaveAs(tranfile2+".xlsx",FileFormat=51) #另存为xls格式

win32 module见:https://download.csdn.net/download/weixin_43519457/11097853
吐槽:我为啥会写这个,因为arcgis没法添加高版本的excel数据,我安装了accessdatabaseengine.exe仍然没用,问其他人也没有解决,如果有人解决了,欢迎评论,我们私聊。我觉得总得往更高版本走的啊,无力吐槽。为啥不出个补丁打了他,我都装了arcgis10.5了仍然这样。

你可能感兴趣的:(Python)