1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Python Excel xlsx xls csv 格式互转

Python Excel xlsx xls csv 格式互转

时间:2023-07-18 02:51:00

相关推荐

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 0607@author: langGe@file: AutoRestart@describer:excel xlsx /xls /csv之间的格式转换 '''import osfrom 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 Noneif 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])

🌎总结

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

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。