【问题标题】:Openpyxl not modifying cell valueOpenpyxl不修改单元格值
【发布时间】:2021-12-07 18:27:03
【问题描述】:

所以我遇到了一个问题,我试图从 excel 电子表格的单元格中清除一堆换行符。我的程序遇到 \n 时会识别它,但 .strip() 和 .replace('\n', '') 不起作用。我在这里错过了什么?

#!/usr/bin/env python3
""" Clean up undesired whitespace in some excel files """

from openpyxl import Workbook, load_workbook

Filename = input("Enter filename:\n")

wb = load_workbook(filename = Filename)
sheet = wb.active
max_row = sheet.max_row
max_column = sheet.max_column

for row in range(2, max_row + 1):
    for col in range(1, max_column + 1):
        print("In row: {} col: {}".format(row, col))
        cell_obj = str(sheet.cell(row = row, column = col).value)
        if cell_obj is not None:
            if cell_obj[0] == ' ' or cell_obj[-1] == ' '
                cell_obj.strip()
            if '\n' in cell_obj:
                cell_obj.replace('\n', '')
                cell_obj.strip('\n')
            if str('\n') in cell_obj:
                cell_obj.replace(str('\n'), '')
            if '\\n' in cell_obj:
                cell_obj.strip('\\n')
        sheet.cell(row=row, column=col).value = cell_obj
wb.save(filename=Filename)

【问题讨论】:

    标签: python excel openpyxl removing-whitespace


    【解决方案1】:

    strip 和 replace 方法返回转换后的结果。它们不作用于原始的不可变字符串。您正在丢弃结果。

    >>> a = 'test\n'
    >>> a.strip()
    'test'
    >>> a
    'test\n'
    >>> b = a.strip()
    >>> b
    'test'
    

    【讨论】:

    • 谢谢@Passerby!伙计,我觉得自己忘记了这一点很傻,但现在我们走在了正确的轨道上!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2017-12-23
    相关资源
    最近更新 更多