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()

全部代码:
封装了一个类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])

🌎总结

23

7

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

  • 🚩如果这篇博客对你有帮助,请 “点赞” “评论”“收藏”一键三连 哦!码字不易,大家的支持就是我坚持下去的动力。
    18
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蚂蚁小兵

慢慢长夜磨一章好文章,费烟!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值