我首先要提到我正在使用 Python 2.7 和 Openpyxl 2.4.1
基本上我正在清理工作簿中的一张工作表。我正在检查每个单元格并检查是否有删除线文本。假设我正在查看 A 列:
for i in range(1, sheet.max_row+1):
my_cell = sheet['A'+str(i)]
if my_cell.font.strikethrough == True:
#here's the tricky part
我知道可以确定单元格是否包含删除线字符,但我想找到 cell.value 中的哪些字符是删除线字符。我已阅读文档,但找不到太多相关内容。这可以用 openpyxl 实现吗?
不,这是不可能的:openpyxl 不处理单元格级别以下的格式。您需要编写自己的解析器来执行此操作。
这可以通过属性实现
Cell.font.strike
:
if my_cell.font.strike ==True:
#here's the tricky part
如果有人在研究较新版本的 openpyxl 的解决方案时遇到此问题:从 openpyxl 版本 3.1.0 开始,可以将
richt_text=True
传递给 load_workbook
函数以启用富文本解析。
如果单元格的一部分有删除线,则打印以下代码:
import openpyxl
from openpyxl.cell.rich_text import CellRichText
wb = openpyxl.load_workbook("Some_Workbook.xlsx", rich_text=True)
sheet = wb["Sheet1"]
for i in range(1, sheet.max_row+1):
my_cell = sheet["A"+str(i)]
if type(my_cell.value) == CellRichText:
for text in my_cell.value:
if text.font.strike:
print(text, "is strikethrough")
else:
print(text, "is not strikethrough")
else:
print(my_cell.value, "is not strikethrough")