背景
由于其他部门给的数据是 csv 文件,业务人员一般都是熟悉 excel 文件,为了方便查看数据,因此需要写个程序,把 csv 文件转换为 excel 文件,由于是经常使用,小编的脚本程序,写成了在命令行中使用的方式
业务人员直接打开 csv 文件会乱码,因excel 默认的编码是 GB2312,其他部门给的基本都是 utf-8 编码,所以会乱码
完整脚本
为了方便在命令行中使用,该脚本使用了 argparse
库,如果对该库不是很懂,可以查看相关资料,进行学习
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 | """ =========================== @Time : 2023/2/1 11:19 @File : csv_to_excel.py @Software: PyCharm @Platform: Win10 @Author : DataShare =========================== """ import pandas as pd import argparse if __name__ = = '__main__' : parser = argparse.ArgumentParser(description = 'csv_to_excel' ) parser.add_argument( '--input_file' , '-in' , type = str , required = True , help = 'csv文件' ) parser.add_argument( '--output_file' , '-out' , type = str , required = False , default = None , help = 'excel文件' ) args = parser.parse_args() data = pd.read_csv(args.input_file, sep = ',' , dtype = 'str' , quotechar = '"' , header = 0 ) print ( 'csv文件行数为:' , len (data)) # 判断数据行数是否一致,防止不可见字符,例如:回车 等 if args.output_file is not None : if args.output_file.endswith( '.xlsx' ): output_file_converted = args.output_file else : output_file_converted = args.output_file + '.xlsx' else : output_file_converted = args.input_file.split( '.csv' )[ 0 ] + '.xlsx' # 这是由于Excel单个工作表限制URL类型数据量为65530,超出的部分会被舍弃 # 只要将strings_to_urls自动转换功能关闭就好了 writer = pd.ExcelWriter(output_file_converted, engine = 'xlsxwriter' , engine_kwargs = { 'options' : { 'strings_to_urls' : False }}) data.to_excel(writer, index = False ) writer.close() print ( '数据转换完成' ) |
使用教程
前提条件:
- 需要把以上的完整脚本,复制下来保存为
csv_to_excel.py
文件 - 本机安装了python,并且在命令行中可以直接使用
使用教程:
最好把 csv_to_excel.py
文件与将要转换的 csv 文件放到一个文件夹中
用法1:
只指定需要转换的 csv 文件,转换后的结果 excel 文件,默认与 csv 文件同名,且保存在同一个文件夹里面
1 2 3 | python csv_to_excel.py - in test.csv #python csv_to_excel.py --input_file test.csv |
用法2:
指定需要转换的 csv 文件,同时指定输出的 excel 结果文件名
1 2 3 | python csv_to_excel.py - in test.csv - out test_convert.xlsx #python csv_to_excel.py --input_file test.csv --output_file test_convert.xlsx |
xlwt 操作
使用xlwt 操作 excel, 保存 .xls 后缀的文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import xlwt def csv_xls(filename, xlsname): f = open (filename, 'r' , encoding = 'utf-8' ) xls = xlwt.Workbook() sheet = xls.add_sheet( 'sheet1' , cell_overwrite_ok = True ) x = 0 for line in f: for i in range ( len (line.split( ',' ))): print (i) item = line.split( ',' )[i] sheet.write(x, i, item) x + = 1 f.close() xls.save(xlsname) if __name__ = = "__main__" : filename = "test1.csv" xlsname = "res1.xls" csv_xls(filename,xlsname) |
xlwt 库仅支持.xls 后缀,不支持.xlsx 后缀的excel 文件
openpyxl 操作
使用openpyxl 库将 csv 转成 .xlsx格式。
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 | from openpyxl import Workbook import datetime def csv_to_xlsx_pd(sourcePath: str ,savePath: str ,encode = 'utf-8' ): """将csv 转为 excel(.xlsx格式) 如果不需要可以把计时相关代码删除 Args: sourcePath:str 来源文件路径 savePath:str 保存文件路径,需要包含保存的文件名,文件名需要是 xlsx 格式的 encode='utf-8' 默认编码,可以改为需要的编码如gbk """ print ( '开始处理%s' % sourcePath) curr_time = datetime.datetime.now() print (curr_time) f = open (sourcePath, 'r' , encoding = encode) # 创建一个workbook 设置编码 workbook = Workbook() # 创建一个worksheet worksheet = workbook.active workbook.title = 'sheet' for line in f: row = line.split( ',' ) worksheet.append(row) # if row[0].endswith('00'): # 每一百行打印一次 # print(line, end="") workbook.save(savePath) print ( '处理完毕' ) curr_time2 = datetime.datetime.now() print (curr_time2 - curr_time) if __name__ = = '__main__' : source = 'source.csv' save = 'result.xlsx' csv_to_xlsx_pd(sourcePath = source, savePath = save, encode = 'utf-8' ) |
数据量小于1w操作会比较快,数据量大于50w, workbook.save() 保持数据会很慢,有时候需要20-30分钟才能保存完成。
使用 pandas 转d
使用 pandas 将csv 转xlsx
1 2 3 4 5 6 7 8 9 10 | import pandas as pd def csv_to_xlsx_pd(): csv = pd.read_csv( 'source.csv' , encoding = 'utf-8' ) csv.to_excel( 'result.xlsx' , sheet_name = 'data' ) #学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441 if __name__ = = '__main__' : csv_to_xlsx_pd() |
数据量小于1w操作会比较快,数据量大于50w,保存会很慢。
到此这篇关于Python把csv文件转换为excel文件的文章就介绍到这了,更多相关Python csv转换为excel内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!