【问题标题】:Openpyxl save does not actually save?Openpyxl保存实际上并没有保存?
【发布时间】:2022-07-29 14:46:41
【问题描述】:

我有一个正在使用 openpyxl 修改的工作簿。

运行代码后,我可以看到公式正在写入 excel 文件中,但它会打印一个空的 df。 (如果我打开excel文件并手动点击保存,打印出来的df数据是正确的)。

谁能解释一下如何让 read_excel 读取该单元格中的值而不是公式?

from openpyxl import load_workbook
import pandas as pd


file_path = "Test.xlsx"
workbook = load_workbook(file_path)
workbook["Temp"]["A1"] = f"=SUM(2+2)"
workbook.save(file_path)
df = pd.read_excel(file_path, header=None)
print(df)  # empty df??

【问题讨论】:

  • 我无法重现该问题,但通常最好先使用 workbook.close() 关闭文件,然后再通过其他机制读取文件。

标签: python python-3.x excel openpyxl


【解决方案1】:

我通过阅读源码定位到这里的问题

pandas.io.excel._openpyxl.OpenpyxlReader._convert_cell


    def _convert_cell(self, cell, convert_float: bool) -> Scalar:
        ......
        # Here, cell.value leads to "" and I guess pandas has no parsing formula
        if cell.value is None:
            return ""  # compat with xlrd
        .....
        return cell.value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2013-07-18
    • 2022-08-11
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多