You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用openpyxl写入Excel时出现‘Removed Records: Formula’错误求助

解决Excel打开时的公式修复提示问题

你遇到的问题是因为Excel将某些内容(包括列名或单元格值)误识别为无效公式,触发自动修复机制。以下是针对性的解决方案:

1. 清洗列名中的公式触发字符

Excel会把列标题里以=、+、-、@开头的字符当成公式处理,即使是表头也会引发报错。先检查并清洗列名:

# 移除列名开头的公式触发字符
df.columns = df.columns.str.replace(r'^[=\+\-@]', '', regex=True)
# 也可替换为友好字符,比如把=换成"等于"
# df.columns = df.columns.str.replace('=', '等于', regex=False)

2. 强制所有单元格以纯文本格式写入

使用openpyxl引擎,将所有单元格设置为文本格式,彻底避免Excel解析为公式:

from pandas import ExcelWriter
from openpyxl.styles import numbers

# 替换原有的df.to_excel代码
with ExcelWriter('C:\\Users\\JohnG\\Downloads\\file.xlsx', engine='openpyxl') as writer:
    df.to_excel(writer, index=False)
    worksheet = writer.sheets['Sheet1']
    # 遍历所有单元格,设置文本格式
    for col in worksheet.columns:
        for cell in col:
            cell.number_format = '@'

3. 批量处理单元格内容中的公式触发字符

如果单元格值存在=、+、-开头的内容,可在字符前加单引号,强制Excel识别为纯文本:

# 处理所有字符串类型的列
for col in df.select_dtypes(include=['object']).columns:
    df[col] = df[col].str.replace(r'^[=\+\-@]', r"'\\g<0>", regex=True)

完整修改后的代码示例

import os
import snowflake.connector
import pandas as pd
from pandas import ExcelWriter
from openpyxl.styles import numbers

# SQL Code - Removed for Privacy

# Execute the query
cursor_clm_dm = conn_clm_dm.cursor()
cursor_clm_dm.execute(query)

# Fetch the results
results = cursor_clm_dm.fetchall()

# Convert the results to a Pandas DataFrame
columns = [desc[0] for desc in cursor_clm_dm.description]
df = pd.DataFrame(results, columns=columns)

# Close the cursor and connection
cursor_clm_dm.close()
conn_clm_dm.close()
conn_clm_dw.close()

# Display the DataFrame
print(df)

# 清洗列名
df.columns = df.columns.str.replace(r'^[=\+\-@]', '', regex=True)

# 处理单元格内容
for col in df.select_dtypes(include=['object']).columns:
    df[col] = df[col].str.replace(r'^[=\+\-@]', r"'\\g<0>", regex=True)

# 以文本格式写入Excel
with ExcelWriter('C:\\Users\\JohnG\\Downloads\\file.xlsx', engine='openpyxl') as writer:
    df.to_excel(writer, index=False)
    worksheet = writer.sheets['Sheet1']
    for col in worksheet.columns:
        for cell in col:
            cell.number_format = '@'

print('done')

内容的提问来源于stack exchange,提问作者John G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 01:47:29