如何从多个文件中提取相同的Excel工作表?

时间:2019-11-13 21:15:37

标签: python excel

我有一个包含类似excel文件的目录,并且想要从每个文件中提取第一张工作表并将其另存为.csv文件。当前具有可从单个文件中提取和保存工作表的代码:

import glob
import pandas as pd

f = glob.glob('filename.xlsx') # assume the path
for excel in f:
    out = excel.split('.')[0]+'.csv'
    df = pd.read_excel(excel) # if only the first sheet is needed.
    df.to_csv(out) 

1 个答案:

答案 0 :(得分:0)

您可以使用具有列表理解功能的glob将所有文件放入列表中:

files_to_be_read = glob.glob("*.xlsx") #Assuming you also have the path to the folder where the excel files are saved
for i in files_to_be_read:
    df_in = pd.read_excel(i) #You pass the path, pd.read_excel always uses the first sheet by default
    df_out = pd.to_csv(i+'.csv') #You will save the file with the same name, but in csv format