【问题标题】:Extracting CSV files from multiple .xlxs files with multiple worksheets [answered]从具有多个工作表的多个 .xlxs 文件中提取 CSV 文件 [已回答]
【发布时间】:2020-11-10 10:19:29
【问题描述】:

为了撰写我的机械工程论文,我收到了很多传感器数据,这些数据配置在多个 Excel 文件 (100) 和多张表 (22) 中。 现在我想将其可视化为 Power Bi,但 .xlxs 文件是一种减慢速度的工作方式,因此我希望将所有数据(表格)保存在单独的 CSV 文件中。 我没有任何真正的编程经验,但能够在 jupyter 或 spyder 中运行脚本。

我在 VBA 中尝试了将多个 Excel 配置到 csv 中的代码,但这仅适用于 .xlsx 文件中的第一张工作表。

我还在 jupyter notebook 中使用了下面的代码;但这给了我一个excel的所有表格。

data = pd.read_excel('file_name.file_format', sheet_name=None)

for sheet_name, df in data.items():
    df.to_csv(f'{sheet_name}.csv')

是否有人有用于此目的的代码,或者是否有人知道如何调整上面的代码以对文件夹中的所有 excel 文件执行此操作?

【问题讨论】:

  • 澄清一下,您是说您需要另一个嵌套现有循环的 for 循环,外部循环扫描文件夹中的每个文件?
  • 正确,并且可能会将原始文件的名称添加到工作表中

标签: python excel csv export-to-csv


【解决方案1】:

只要每个文件中的工作表名称相同,那么这应该可以工作:

import os
import pandas as pd

# target directory where the workbooks lie
tgt_dir = r'paste\directory\here\make\sure\to\keep\letter\r\before\quote'

# list of any files within the dir that have .xlsx in them
list_xl_files = [f for f in os.listdir(tgt_dir) if '.xlsx' in f.lower()]

# type a list of the sheets you want to target and extract
list_target_sheets = ['Sheet1', 'Sheet2', 'etc']

# iterate through each file and for each sheet in target sheets
for xl_file in list_xl_files:
    for sheet in list_target_sheets:
        
        # read in the file and target sheet
        df = pd.read_excel(tgt_dir+'\\'+xl_file, sheet_name=sheet)
        
        # export to csv but replace .xlsx with nothing 
        # then add _sheetname.csv so the filename shows the sheet too
        df.to_csv(tgt_dir+'\\'+xl_file.replace('.xlsx','')+'_'+sheet_name+'.csv')

【讨论】:

  • 不幸的是,有些文件有额外的传感器和数据,这意味着额外的工作表。但我现在得到了这段代码:import os import pandas as pd directory = "./" files = os.listdir(directory) for xlxs_file in files: if ".xlsx" in xlxs_file: filename = xlxs_file.strip(".xlsx") xlxs_file = os.path.join(directory, xlxs_file) data = pd.read_excel(xlxs_file, sheet_name=None) for sheet_name, df in data.items(): df.to_csv("{}-{}.csv".format(filename, sheet_name))
  • 真好。请发布您的答案并将此主题标记为已回答,以便其他来到这里的人也可以学习,而无需深入研究 cmets。干杯!
【解决方案2】:

您可以尝试遍历每个具有 .xlxs 的文件的目录,只需将 YOUR_DIR 替换为您自己的包含文件的文件夹路径。

我添加了“文件名”,它只是没有扩展名的文件名,因此您可以将其添加到 .csv 文件名中

import os

directory = "\\YOUR_DIR\\HERE"
files = os.listdir(directory)

for xlxs_file in files:
    if ".xlxs" in xlxs_file:

        filename = xlxs_file.strip(".xlxs")
        xlxs_file = directory + "\\" + xlxs_file

        data = pd.read_excel(xlxs_file, sheet_name=None)
        for sheet_name, df in data.items():
            df.to_csv(f'{filename}_{sheet_name}.csv')

【讨论】:

  • 不幸的是它似乎没有工作,它只生成文件夹中第一个文件的工作表
  • @Tigerfire176 这很奇怪,它们都具有相同的扩展名吗?你能把“print(xlxs_file)”放在xlxs_file:的“if”.xlxs下,看看它是否列出了文件?
  • 啊我犯了一个错误 - 已编辑代码 sn-p 进行更正
  • 我试着逐行运行它! ``` 用于文件中的 xlxs_file:文件“”,文件中 xlxs_file 的第 1 行:^ SyntaxError:解析时出现意外 EOF ```
  • 抱歉,不知道该建议什么 - 我尝试了几本包含多张工作表的工作簿,并获得了预期的结果。复制到 SO 后可能存在格式/缩进问题。听起来好像没有在“for xlxs_file in files:”下找到代码块:
【解决方案3】:

不幸的是,有些文件有额外的传感器和数据,这意味着额外的工作表。但我现在得到了这段代码:

import os
import pandas as pd

directory = "./"
files = os.listdir(directory)
for xlxs_file in files:
    if ".xlsx" in xlxs_file:
        filename = xlxs_file.strip(".xlsx")
        xlxs_file = os.path.join(directory, xlxs_file)
        data = pd.read_excel(xlxs_file, sheet_name=None)
        for sheet_name, df in data.items():
            df.to_csv("{}-{}.csv".format(filename, sheet_name))

【讨论】:

    猜你喜欢
    • 2020-11-30
    • 2020-11-27
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 2014-05-20
    相关资源
    最近更新 更多