递归替换 excel 文件目录中的字符串

Recursively replace string in directory of excel files

我正在尝试用 excel 文件目录中的另一个字符串替换给定字符串的每次出现。

for (root, dirs, files) in os.walk(DIRECTORY):
    for file in files:
        if file.endswith(".xlsx"):
            path = os.path.join(root, file)
            print("Opening: " + path)
            wb = openpyxl.load_workbook(path)
            for ws in wb.worksheets:
                for row in ws.iter_rows():
                    for cell in row:
                        print(cell.value)
                        if cell.value == target:
                            print("TARGET STRING FOUND")
                            cell.value = replace
                wb.save(wb)

当我 运行 脚本时,我得到 AttributeError: 'list' object has no attribute 'endswith'

感谢您的帮助

试试这个

basepath="directory_path"
files = list(filter(lambda x: '.xlsx' in x, os.listdir(basepath)))
for file in files:
    wb = openpyxl.load_workbook(f"{basepath}/file")
    for sheet in wb.worksheets:
        for cell in sheet.iter_rows('C{}:C{}'.format(sheet.min_row,sheet.max_row)):
            print(cell + "\n")
            if cell.value == target:
                cell.value = replace

os.walk 不是 return 文件序列。它产生(root,dirs,files)。

for (root, dirs, files) in os.walk(directory):
    for name in files:
        if name.endswith(".xlsx"):
            path = os.path.join(root, name)
            # the rest of your code here