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)
剥离和替换方法 return 转换后的结果。它们不作用于原始的不可变字符串。您正在丢弃结果。
>>> a = 'test\n'
>>> a.strip()
'test'
>>> a
'test\n'
>>> b = a.strip()
>>> b
'test'
所以我 运行 遇到了一个问题,我试图从 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)
剥离和替换方法 return 转换后的结果。它们不作用于原始的不可变字符串。您正在丢弃结果。
>>> a = 'test\n'
>>> a.strip()
'test'
>>> a
'test\n'
>>> b = a.strip()
>>> b
'test'