将XLSX工作簿保存为多个CSV文件



尝试将包含多个工作表的Excel文件另存为相应的CSV文件。我尝试了以下方法:

import xlrd
from openpyxl import Workbook, load_workbook
import pathlib
import shutil
import pandas as pd
def strip_xlsx(inputdir, file_name, targetdir):
wb = load_workbook(inputdir)
sheets = wb.sheetnames
for s in sheets:
temp_df = pd.read_excel(inputdir, sheet_name=s)
temp_df.to_csv(targetdir + "/" + file_name.strip(".xlsx") + "_" + s + ".csv", encoding='utf-8-sig')

其中inputdir是Excel文件的绝对路径(例如:"/Users/me/test/t.xlsx"), file_name只是文件的名称("t.xlsx"), target_dir是我希望保存csv文件的路径。

这些方法效果很好,但速度很慢。我是Python的新手,感觉我以一种非常低效的方式实现了这个方法。

感谢大师们的指点。

如果你把所有的东西都放在熊猫里,你可能会有更好的运气。我看到您正在使用openpyxl来获取表名,您可以在pandas中这样做。至于速度,你只需要看到:

编辑:

正如Charlie(可能是世界上最了解openpyxl的人)指出的那样,只使用openpyxl会更快。在这种情况下,大约快25% (9.29 ms ->我的两张纸测试6.87毫秒):

from os import path, mkdir
from openpyxl import load_workbook
import csv
def xlsx_to_multi_csv(xlsx_path: str, out_dir: str = '.') -> None:
"""Write each sheet of an Excel file to a csv
"""
# make the out directory if it does not exist (this is not EAFP)
if not path.exists(out_dir):
mkdir(out_dir)
# set the prefix
prefix = path.splitext(xlsx_path)[0]
# load the workbook
wb = load_workbook(xlsx_path, read_only=True)
for sheet_name in wb.sheetnames:
# generate the out path
out_path = path.join(out_dir, f'{prefix}_{sheet_name}.csv')
# open that file
with open(out_path, 'w', newline='') as file:
# create the writer
writer = csv.writer(file)
# get the sheet
sheet = wb[sheet_name]
for row in sheet.rows:
# write each row to the csv
writer.writerow([cell.value for cell in row])
xlsx_to_multi_csv('data.xlsx')

您只需要指定保存csv文件的路径,并遍历pandas创建的字典以将框架保存到该目录。

csv_path = 'pathtodir'
for name,df in pd.read_excel('xl_path',sheet_name=None).items():
df.to_excel(os.path.join(csv_path,name)

最新更新