【问题标题】:Can I use python to loop through multiple excel files and add individual sheets to a master workbook?我可以使用 python 循环遍历多个 excel 文件并将单个工作表添加到主工作簿吗?
【发布时间】:2021-08-04 04:44:18
【问题描述】:

长话短说:我正在尝试创建一个程序,该程序循环访问存储在本地计算机上的 excel 文件,并将每个 excel 文件中的工作表添加到主工作簿中。

注意:我不想使用 pandas dataframe.append,因为每张表都有唯一的信息,我想单独保留每张表。

任何帮助将不胜感激!

【问题讨论】:

  • 是的。创建一个字典以将每个 Excel 文件存储为一个单独的数据框,然后将字典中的每个数据框写为单个 Excel 文件中的一张表。
  • 如果 excel 文件有多个工作表,这会起作用吗?
  • 它会起作用,但可能需要例外/等。处理任何特殊情况。如果无法访问您的数据文件,就无法说出如何

标签: python excel pandas


【解决方案1】:

我认为使用 openpyxl 将是最简单的解决方案。它可以让您阅读和编写 Excel 工作表,甚至可以选择创建各种工作表。就个人而言,这是我在使用 excel 时最喜欢的路线。

【讨论】:

    【解决方案2】:

    您可以使用 pandas,因为它可以从 excel 文件导入和导出特定工作表:

    import pandas as pd
    
    sheet1 = pd.read_excel(filepath=r'C:\xlsfile.xlsx', sheet_name='Sheet 1')
    sheet2 = pd.read_excel(filepath=r'C:\xlsfile.xlsx', sheet_name='Sheet 2')
    sheet3 = pd.read_excel(filepath=r'C:\anotherfile.xlsx', sheet_name='Sheet 1')
    sheet4 = pd.read_excel(filepath=r'C:\athirdfile.xlsx', sheet_name='Sheet 1')
    
    outputfile = r'C:\output.xlsx'
    
    sheet1.to_excel(outputfile, sheet_name='Sheet 1-1')
    sheet2.to_excel(outputfile, sheet_name='Sheet 1-2')
    sheet3.to_excel(outputfile, sheet_name='Sheet 2-1')
    sheet4.to_excel(outputfile, sheet_name='Sheet 3-1')
    

    这会从 3 个单独的文件中读取 4 张单张纸,并创建一个包含 4 张纸的输出文件。

    【讨论】:

      【解决方案3】:
      You could do something along the lines: 
      
      import pandas as pd # pandas module for dataframes
      import os  #module to get working directory
      import xlrd# module to open excel files
      from openpyxl import load_workbook #other module to open excel files
      gbl = globals()
      cwd =os.getcwd() # get the path to the current locaction
      folders =[x for x in os.listdir() if "." not in x] # check for the folder with all the excels
      path=cwd+"\\{}".format(folders[0]) # get the path to that folder
      # listado de curso 
      files = os.listdir(path)    # path to files 
      files = list(filter(lambda f: f.endswith('.xls'), files))+list(filter(lambda f: f.endswith('.xlsx'), files))
      files = [x for x in files if "~$" not in x]
      writer = pd.ExcelWriter('multiple.xlsx', engine='xlsxwriter')
      for x in files:
          workbook = pd.read_excel(path+"/"+x,sheet_name = None)
          for i in workbook.keys():
              gbl["workbook"+x+i] = workbook[i].copy()
              print("workbook"+x+i)
              gbl["workbook"+x+i].to_excel(writer, sheet_name=x+i)
      writer.save()
      

      我已经对其进行了编辑,因此您可以使用具有不同工作表的 excel 文件来完成它。

      【讨论】:

      • 我希望这能回答你的问题
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多