openpyxl-写以等号('=')开头的字符串

时间:2020-09-04 19:42:08

标签: python excel openpyxl

我正在从数据库中提取一些随机文本字符串,并使用openpyxl将它们写入xlsx文件。一些字符串碰巧以等号开头(类似“ = 134lj9adsasf&^”),这导致Excel试图将其解释为公式并将其显示为“ #NAME?”的问题。由于错误。

在Excel本身中,可以通过在写入字符串之前将单元格的格式从“常规”更改为“文本”来避免此问题。我试图用openpyxl做到这一点,但没有任何区别。当我打开生成的电子表格时,它确实显示该单元格为文本格式,但仍然显示错误。我该如何解决?

下面是一个工作示例。当我在Excel中打开文件时,它显示#NAME?对于第三个单元。但是,如果我只是选择该单元格并键入“ = abc?123”(不带引号),则Excel会接受没有问题的文本。

import openpyxl
from openpyxl.cell.cell import Cell

stringList = [("abc","123","=abc?123","ok")]
wb = openpyxl.Workbook()
ws = wb.create_sheet('Sheet1')
for row in stringList:
    ws.append(row)
    for idx, cell in enumerate(ws[ws.max_row]):
        cell.number_format = '@'  # Set all cells to text format to avoid issue with =
        cell.value = str(row[idx]) # Re-write data
wb.save("filename.xlsx")

1 个答案:

答案 0 :(得分:1)

我知道了。只需更改data_type而不是number_format。

以equals开头的字符串的data_type设置为“ f”。

for row in stringList:
    ws.append(row)
    for cell in ws[ws.max_row]:
        if cell.data_type == 'f':
            cell.data_type = 's'

excel