尝试将包含多个工作表的 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 的新手,感觉我以一种非常低效的方式实现了该方法。
希望得到大师们的建议。
答案 0 :(得分:2)
如果你把所有东西都保存在 Pandas 中,你的运气可能会更好。我看到您正在使用 openpyxl 来获取工作表名称,您可以在 Pandas 中执行此操作。至于速度,你只需要看看:
编辑:
正如查理(这个星球上可能最了解 openpyxl 的人)指出的那样,只使用 openpyxl 会更快。在这种情况下,速度提高了大约 25%(对于我的两页测试,9.29 毫秒 -> 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')
答案 1 :(得分:1)
您只需要指定一个保存 csv 的路径,并遍历由 Pandas 创建的字典以将帧保存到目录中。
csv_path = '\path\to\dir'
for name,df in pd.read_excel('xl_path',sheet_name=None).items():
df.to_excel(os.path.join(csv_path,name)