【问题标题】:Converting Excel file with multiple sheets into multiple csv files using Jupyter notebook使用 Jupyter notebook 将具有多个工作表的 Excel 文件转换为多个 csv 文件
【发布时间】:2020-11-27 04:03:49
【问题描述】:

我有一个包含多张工作表的 excel 文件。我想将这些工作表转换为单独的 CSV 文件。

我尝试了这段代码,得到了一份有序的工作表字典。现在我需要一步将它们保存为 CSV 文件,而不必在单独的步骤中手动保存每个文件

xls = pd.ExcelFile('file.xlsx')
sheets = {}
for sheet_name in xls.sheet_names:
    sheets[sheet_name] = xls.parse(sheet_name)

【问题讨论】:

    标签: python python-3.x excel pandas jupyter-notebook


    【解决方案1】:

    您可以使用to_csv 将数据框保存为 csv 文件:

    # I prefer reading excel with pd.read_excel
    # passing `sheet_name=None` returns a dictionary 
    # with the form {sheet_name: dataframe}
    data = pd.read_excel('file.xlsx', sheet_name=None)
    
    # loop through the dictionary and save csv
    for sheet_name, df in data.items():
        df.to_csv(f'{sheet_name}.csv')
    

    【讨论】:

    • f before{sheet_name} 代表什么?
    • @Michael that f-string 在 Python 3 中。
    • 不熟悉pandas的朋友,pd来自import pandas as pd
    猜你喜欢
    • 2019-04-16
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 2018-04-28
    相关资源
    最近更新 更多