【问题标题】:Adding Multiple .xls files to a Single .xls file, using the file name to name tabs将多个 .xls 文件添加到单个 .xls 文件中,使用文件名命名选项卡
【发布时间】:2018-08-14 17:49:48
【问题描述】:

我有多个目录,每个目录都包含任意数量的 .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))

【问题讨论】:

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


    【解决方案1】:

    你可以试试

    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()
    

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

    【讨论】:

      【解决方案2】:

      这是一个小辅助函数 - 它同时支持 .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')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-06
        相关资源
        最近更新 更多