【问题标题】:Update a specific sheet name in all the excels inside a folder更新文件夹内所有 excel 中的特定工作表名称
【发布时间】:2021-10-16 15:50:40
【问题描述】:

在一个文件夹中,我有 50 个 excel 文件,每个文件中有多个工作表。我必须更新这些文件中工作表的名称,其中 sheet_name 包含“XYZ”。

因此,对于每个文件,如果 sheet_name 具有“XYZ”,则将该 sheet_name 更改为“ABC”。我尝试使用以下代码遍历文件,但无法编写代码来更改工作表名称:

filelist=[]
for path, subdirs, files in os.walk(directory):
    for file in files:
        if (file.endswith('.xlsx') or file.endswith('.xls') or file.endswith('.XLS')):
            filelist.append(os.path.join(path, file))

【问题讨论】:

    标签: python python-3.x pandas dataframe python-2.7


    【解决方案1】:

    您可以这样简化以列出文件:

    import os
    mypath = r'C:\your\files\path'
    filenames = [x for x in os.listdir(mypath) if x.endswith('.xls') or x.endswith('.xlsx') or x.endswith('.XLS')]
    for filename in filenames:
        a = filename.replace('XYZ','ABC')
        os.rename(mypath+"/"+filename,mypath+"/"+a)
    

    【讨论】:

      【解决方案2】:

      你可以使用openpyxl和glob

      import glob
      from openpyxl import load_workbook
      paths = glob.glob("directory*xls*") + glob.glob("directory*XLS*")
      for path in paths:
          wb = load_workbook(path)
          for sheetname in wb.sheetnames:
              ws = wb[sheetname]
              if "XYZ" in ws.title:
                  ws.title = "ABC"
          wb.save(path)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-06
        • 2018-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多