Python把csv文件轉(zhuǎn)換為excel文件
背景
由于其他部門給的數(shù)據(jù)是 csv 文件,業(yè)務(wù)人員一般都是熟悉 excel 文件,為了方便查看數(shù)據(jù),因此需要寫個程序,把 csv 文件轉(zhuǎn)換為 excel 文件,由于是經(jīng)常使用,小編的腳本程序,寫成了在命令行中使用的方式
業(yè)務(wù)人員直接打開 csv 文件會亂碼,因excel 默認(rèn)的編碼是 GB2312,其他部門給的基本都是 utf-8 編碼,所以會亂碼
完整腳本
為了方便在命令行中使用,該腳本使用了 argparse
庫,如果對該庫不是很懂,可以查看相關(guān)資料,進(jìn)行學(xué)習(xí)
""" =========================== @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文件行數(shù)為:', len(data)) # 判斷數(shù)據(jù)行數(shù)是否一致,防止不可見字符,例如:回車 等 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類型數(shù)據(jù)量為65530,超出的部分會被舍棄 # 只要將strings_to_urls自動轉(zhuǎn)換功能關(guān)閉就好了 writer = pd.ExcelWriter(output_file_converted, engine='xlsxwriter', engine_kwargs={'options': {'strings_to_urls': False}}) data.to_excel(writer, index=False) writer.close() print('數(shù)據(jù)轉(zhuǎn)換完成')
使用教程
前提條件:
- 需要把以上的完整腳本,復(fù)制下來保存為
csv_to_excel.py
文件 - 本機(jī)安裝了python,并且在命令行中可以直接使用
使用教程:
最好把 csv_to_excel.py
文件與將要轉(zhuǎn)換的 csv 文件放到一個文件夾中
用法1:
只指定需要轉(zhuǎn)換的 csv 文件,轉(zhuǎn)換后的結(jié)果 excel 文件,默認(rèn)與 csv 文件同名,且保存在同一個文件夾里面
python csv_to_excel.py -in test.csv #python csv_to_excel.py --input_file test.csv
用法2:
指定需要轉(zhuǎn)換的 csv 文件,同時指定輸出的 excel 結(jié)果文件名
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 后綴的文件
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 轉(zhuǎn)成 .xlsx格式。
from openpyxl import Workbook import datetime def csv_to_xlsx_pd(sourcePath:str,savePath:str,encode='utf-8'): """將csv 轉(zhuǎn)為 excel(.xlsx格式) 如果不需要可以把計時相關(guān)代碼刪除 Args: sourcePath:str 來源文件路徑 savePath:str 保存文件路徑,需要包含保存的文件名,文件名需要是 xlsx 格式的 encode='utf-8' 默認(rèn)編碼,可以改為需要的編碼如gbk """ print('開始處理%s' % sourcePath) curr_time = datetime.datetime.now() print(curr_time) f = open(sourcePath, 'r', encoding=encode) # 創(chuàng)建一個workbook 設(shè)置編碼 workbook = Workbook() # 創(chuàng)建一個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')
數(shù)據(jù)量小于1w操作會比較快,數(shù)據(jù)量大于50w, workbook.save() 保持?jǐn)?shù)據(jù)會很慢,有時候需要20-30分鐘才能保存完成。
使用 pandas 轉(zhuǎn)d
使用 pandas 將csv 轉(zhuǎn)xlsx
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') #學(xué)習(xí)中遇到問題沒人解答?小編創(chuàng)建了一個Python學(xué)習(xí)交流群:711312441 if __name__ == '__main__': csv_to_xlsx_pd()
數(shù)據(jù)量小于1w操作會比較快,數(shù)據(jù)量大于50w,保存會很慢。
到此這篇關(guān)于Python把csv文件轉(zhuǎn)換為excel文件的文章就介紹到這了,更多相關(guān)Python csv轉(zhuǎn)換為excel內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python3 requests文件下載 期間顯示文件信息和下載進(jìn)度代碼實例
這篇文章主要介紹了Python3 requests文件下載 期間顯示文件信息和下載進(jìn)度代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08Python使用pdfminer庫玩轉(zhuǎn)PDF文本提取
pdfminer是一個開源的Python第三方庫,專門用于解析PDF文件,本文主要為大家詳細(xì)介紹了如何使用pdfminer實現(xiàn)PDF文本提取,有需要的小伙伴可以了解下2025-02-02Python matplotlib繪圖建立畫布及坐標(biāo)系
這篇文章主要介紹了Python matplotlib繪圖建立畫布及坐標(biāo)系,建立畫布 figsize,它用width和height來控制畫布的寬和高,下面來一起倆姐更多內(nèi)容吧2021-12-12使用Python實現(xiàn)Excel文件轉(zhuǎn)換為SVG格式
SVG(Scalable Vector Graphics)是一種基于XML的矢量圖像格式,這種格式在Web開發(fā)和其他圖形應(yīng)用中非常流行,提供了一種高效的方式來呈現(xiàn)復(fù)雜的矢量圖形,本文將介紹如何使用Python轉(zhuǎn)換Excel文件為SVG格式,需要的朋友可以參考下2024-07-07Python深度學(xué)習(xí)之圖像標(biāo)簽標(biāo)注軟件labelme詳解
這篇文章主要介紹了Python深度學(xué)習(xí)之圖像標(biāo)簽標(biāo)注軟件labelme詳解,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)python的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04Python腳本,標(biāo)識符,變量使用,腳本語句,注釋,模塊引用詳解
這篇文章主要為大家詳細(xì)介紹了Python腳本,標(biāo)識符,變量使用,腳本語句,注釋,模塊引用,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02Python中Timedelta轉(zhuǎn)換為Int或Float方式
這篇文章主要介紹了Python中Timedelta轉(zhuǎn)換為Int或Float方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07python排序函數(shù)sort()與sorted()的區(qū)別
這篇文章主要介紹了python排序函數(shù)sort()與sorted()的區(qū)別,需要的朋友可以參考下2018-09-09