• Python Excel xlsx,xls,csv 格式互转


    常常需要对excel的格式进行转换,借助 win32com 库,可以实现这个功能,下面我封装了下,方便使用。

    win32com 表格处理函数底层,不同的格式有不同的数值对应:
    比如下面我重点圈出来,常用的3个格式:csv/xlsx/xls

    完整的mapping表格,请点击链接 :XlFileFormat enumeration (Excel) | Microsoft Docs

    在这里插入图片描述
    在这里插入图片描述


    核心代码就下面这几句,打开excel,打开表格,SaveAs另存为指定格式
     			excel = DispatchEx('Excel.Application')
                excel.Visible = False  # 如果是True  会打开excel程序(界面)
                excel.DisplayAlerts = 0  # 不显示警告信息
                wb = excel.Workbooks.Open(input_file)  # 打开一个excel文件 最好使用绝对路径
                wb.SaveAs(out_file, FileFormat= 62)  # 另存为xls格式
                wb.Close()
                excel.Application.Quit()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    全部代码:
    封装了一个类ExcelFormat,方便调用,excel_format_transform()函数有两个参数,输入表格文件路径和输出的格式
    运行完后,输入文件的目录下会生成一个同名但是格式不同的表格文件

    '''
    Created on 20220607
    @author: langGe
    @file: AutoRestart
    @describer:
    excel xlsx /xls /csv之间的格式转换 
    '''
    
    import os
    from win32com.client import *
    
    
    class ExcelFormat(object):
        def __init__(self):
            self.excel_format = {"xlsx": 56, "xls": 51, "csv": 62}
    
        def excel_format_transform(self, input_file, excel_type):
            '''
            :param input_file: 输入表格文件
            :param excel_type: 期望转换的格式, csv/xls等
            :return:
            '''
    
            input_file = os.path.abspath(input_file) #必须用绝对路径
            filepath, fullname = os.path.split(input_file)
            name, ext = os.path.splitext(fullname)
    
            if ext == excel_type.lower():
                print("输入表格后缀和期望输出的格式相同")
                return None
    
            if excel_type.lower() not in self.excel_format.keys():
                print("暂不指出该格式{}转换".format(excel_type.lower()))
                return None
    
            '''生成输出文件路径'''
            out_file = "{}.{}".format(name, excel_type.lower())
            out_file = os.path.join(filepath, out_file)
            out_file = os.path.abspath(out_file)
            if os.path.exists(out_file):
                os.remove(out_file)
    
            try:
                excel = DispatchEx('Excel.Application')
                excel.Visible = False  # 如果是True  会打开excel程序(界面)
                excel.DisplayAlerts = 0  # 不显示警告信息
                wb = excel.Workbooks.Open(input_file)  # 打开一个excel文件 最好使用绝对路径
                wb.SaveAs(out_file, FileFormat = self.excel_format[excel_type.lower()])  # 另存为xls格式
                wb.Close()
                excel.Application.Quit()
                print("输出文件", out_file)
                print("转换成功!")
            except Exception as e:
                print("{}表格格式转换失败!".format(input_file))
                print(e)
    
    
    if __name__ == '__main__':
        for i in sys.argv:
            print(i)
        if len(sys.argv) == 3:
            c = ExcelFormat()
            print("输入文件", sys.argv[1])
            c.excel_format_transform(sys.argv[1], sys.argv[2])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64

    🌎总结

    23

    7

    • 🚩要有最朴素的生活,最遥远的梦想,即使明天天寒地冻,路遥马亡!

    • 🚩如果这篇博客对你有帮助,请 “点赞” “评论”“收藏”一键三连 哦!码字不易,大家的支持就是我坚持下去的动力。
      18
  • 相关阅读:
    Excel导出——SheetJS简单使用
    Android 7.1 音量定制限定在0-80%之间可调节
    【问题证明】矩阵方程化为特征值方程求得的特征值为什么是全部特征值?不会丢解吗?
    基于keras构建lstm模型自动生成音乐系统
    Python实现疫情医疗信息管理系统(附源码)
    “1-5-15”原则:中国联通数字化监控平台可观测稳定性保障实践
    什么是Java中的反射(Reflection),如何使用它
    与脑交互最高效的交互方式:深度内部处理 冥想
    SpringCloud-7.消息驱动(Spring Cloud Stream)
    黑客学习笔记(自学)
  • 原文地址:https://blog.csdn.net/qq_34414530/article/details/126608517