简体   繁体   English

Openpyxl 不修改单元格值

[英]Openpyxl not modifying cell value

So I am running into an issue where I am trying to clean a bunch of newlines out of cells in excel spreadsheets.所以我遇到了一个问题,我试图从 excel 电子表格中的单元格中清除一堆换行符。 My program is recognizing \\n when it comes across it but .strip() and .replace('\\n', '') are not working.我的程序在遇到 \\n 时识别它,但 .strip() 和 .replace('\\n', '') 不起作用。 What am I missing here?我在这里缺少什么?

#!/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)

The strip and replace methods return transformed results. strip 和 replace 方法返回转换后的结果。 They do not act on the original immutable string.它们不会作用于原始的不可变字符串。 You are throwing away the results.你扔掉了结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM