簡體   English   中英

將 XLSX 工作簿保存為多個 CSV 文件

[英]Saving XLSX workbooks as multiple CSV files

嘗試將具有多張工作表的 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 的新手,感覺我以非常低效的方式實現了該方法。

不勝感激大師們的建議。

如果您將所有內容都保存在 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')

您只需要指定保存 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM