簡體   English   中英

Openpyxl 不修改單元格值

[英]Openpyxl not modifying cell value

所以我遇到了一個問題,我試圖從 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)

strip 和 replace 方法返回轉換后的結果。 它們不會作用於原始的不可變字符串。 你扔掉了結果。

>>> 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