gpt4 book ai didi

python - 从 Python 到 Excel 的 Excel 公式格式

转载 作者:行者123 更新时间:2023-12-04 20:22:09 24 4
gpt4 key购买 nike

我在将 Pandas 数据导出到 Excel 时遇到问题:
例如,我想导出这样的数据

= 1+2+3
现在,为此,我尝试了两种方法:
d = p.DataFrame({'test1': ["=1+2+3"], 'test2': ["'=1+2+3"]})
d.to_excel('test3.xlsx')
Excel 以这种方式显示列:
test1 test2
6 '=1+2+3
对于test2,我虽然excel会忽略',并将公式视为文本,这是我想要的。但它显示它。你知道我该怎么做吗?
感谢帮助

最佳答案

我建议使用 openpyxl 库(带有 pandas 模块)。
这是一个小例子:

from openpyxl import Workbook, load_workbook

wb = Workbook()
ws = wb.active

# If you want to open an exisiting file you can use instead:
# wb = load_workbook(r'test3.xlsx')

# Add value to cell
ws['A1'] = "test1"
ws['B1'] = "test2"
ws['C1'] = "Total"

# Add formula to cell
ws['A2'] = "=2+3+4"
ws['B2'] = "=1+2+3"
ws['C2'] = "=SUM(A2:B2)"

# To add the Formula string to a cell just change the data_type of that cell
ws['D2'] = "=SUM(A2:B2)"
ws['D2'].data_type = 's'

# Save file
wb.save(r'./test3.xlsx')

# Close
wb.close()
这是 guide关于如何使用 将 Pandas 数据框附加到 Excel 工作表中打开pyxl

关于python - 从 Python 到 Excel 的 Excel 公式格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70155677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com