将多个.xls文件添加到单个.xls文件中,使用文件名命名选项卡

时间:2018-03-06 19:00:26

标签: python excel python-2.7 pandas python-requests

我有多个目录,每个目录包含任意数量的.xls文件。 我想将文件放在任何给定的目录中,并将它们组合成一个.xls文件,使用文件名作为选项卡名称。 例如,如果有文件NAME.xls,AGE.xls,LOCATION.xls,我想将它们与名为NAME的选项卡上的NAME.xls数据合并到一个新文件中,来自AGE.xls的数据一个名为AGE的选项卡,依此类推。 每个源.xls文件只有一列没有标题的数据。 这是我到目前为止所做的,而且它不起作用。 任何帮助将不胜感激(我对Python很新,我以前从未做过这样的事情。)

wkbk = xlwt.Workbook()

xlsfiles =  glob.glob(os.path.join(path, "*.xls"))
onlyfiles = [f for f in listdir(path) if isfile(join(path, f))]
tabNames = []
for OF in onlyfiles:
    if str(OF)[-4:] == ".xls":
        sheetName = str(OF)[:-4]
        tabNames.append(sheetName)
    else:
        pass

for TN in tabNames:
    outsheet = wkbk.add_sheet(str(TN))
    data = pd.read_excel(path + "\\" + TN + ".xls", sheet_name="data")
    data.to_excel(path + "\\" + "Combined" + ".xls", sheet_name = str(TN))

2 个答案:

答案 0 :(得分:0)

你能试试吗

import pandas as pd
import glob

path = 'YourPath\ToYour\Files\\' # Note the \\ at the end

# Create a list with only .xls files
list_xls = glob.glob1(path,"*.xls") 

# Create a writer for pandas
writer = pd.ExcelWriter(path + "Combined.xls", engine = 'xlwt')

# Loop on all the files
for xls_file in list_xls:
    # Read the xls file and the sheet named data
    df_data = pd.read_excel(io = path + xls_file, sheet_name="data") 
    # Are the sheet containing data in all your xls file named "data" ?
    # Write the data into a sheet named after the file
    df_data.to_excel(writer, sheet_name = xls_file[:-4])
# Save and close your Combined.xls
writer.save()
writer.close()

让我知道它是否适合你,我从未尝试过引擎=' xlwt'因为我不使用.xls文件,但.xlsx

答案 1 :(得分:0)

这是一个小帮助函数 - 它支持.xls.xlsx个文件:

import pandas as pd
try:
    from pathlib import Path
except ImportError:              # Python 2
    from pathlib2 import Path


def merge_excel_files(dir_name, out_filename='result.xlsx', **kwargs):
    p = Path(dir_name)
    with pd.ExcelWriter(out_filename) as xls:
        _ = [pd.read_excel(f, header=None, **kwargs)
               .to_excel(xls, sheet_name=f.stem, index=False, header=None)
             for f in p.glob('*.xls*')]

用法:

merge_excel_files(r'D:\temp\xls_directory', 'd:/temp/out.xls')
merge_excel_files(r'D:\temp\xlsx_directory', 'd:/temp/out.xlsx')