[英]Save Pandas DataFrames with formulas to xlsx files
In a Pandas DataFrame i have some "cells" with values and some that need to contain excel formulas.在 Pandas DataFrame 中,我有一些带有值的“单元格”,有些需要包含 excel 公式。 I have read that i can get formulas with我读过我可以得到公式
link = 'HYPERLINK("#Groups!A' + str(someInt) + '"; "LINKTEXT")'
xlwt.Formula(link)
and store them in the dataframe.并将它们存储在dataframe中。
When i try to save my dataframe as an xlsx file with当我尝试将我的 dataframe 保存为 xlsx 文件时
writer = pd.ExcelWriter("pandas" + str(fileCounter) + ".xlsx", engine = "xlsxwriter")
df.to_excel(writer, sheet_name = "Paths", index = False)
# insert more sheets here
writer.save()
i get the error:我得到错误:
TypeError: Unsupported type <class 'xlwt.ExcelFormula.Formula'> in write()
So i tried to write my formula as a string to my dataframe but Excel wants to restore the file content and then fills all formula cells with 0
's.所以我尝试将我的公式作为字符串写入我的 dataframe,但 Excel 想要恢复文件内容,然后用0
填充所有公式单元格。
Edit: I managed to get it work with regular strings but nevertheless would be interested in a solution for xlwt formulas.编辑:我设法让它与常规字符串一起工作,但仍然对 xlwt 公式的解决方案感兴趣。
So my question is: How do i save dataframes with formulas to xlsx files?所以我的问题是:如何将带有公式的数据帧保存到 xlsx 文件中?
Since you are using xlsxwriter, strings are parsed as formulas by default ( "strings_to_formulas: Enable the worksheet.write() method to convert strings to formulas. The default is True" ), so you can simply specify formulas as strings in your dataframe.由于您使用的是 xlsxwriter,因此默认情况下将字符串解析为公式( “strings_to_formulas:启用 worksheet.write() 方法将字符串转换为公式。默认值为 True” ),因此您只需在 dataframe 中将公式指定为字符串即可。
Example of a formula column which references other columns in your dataframe:引用 dataframe 中其他列的公式列示例:
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
writer = pd.ExcelWriter("foo.xlsx", engine="xlsxwriter")
df["product"] = None
df["product"] = (
'=INDIRECT("R[0]C[%s]", 0)+INDIRECT("R[0]C[%s]", 0)'
% (
df.columns.get_loc("col1") - df.columns.get_loc("product"),
df.columns.get_loc("col2") - df.columns.get_loc("product"),
)
)
df.to_excel(writer, index=False)
writer.save()
Produces the following output:产生以下 output:
After writing the df using table.to_excel(writer, sheet_name=...)
, I use write_formula()
as in this example (edited to add the full loop).使用table.to_excel(writer, sheet_name=...)
编写 df 后,我使用write_formula()
作为本例(编辑以添加完整循环)。 To write all the formulas in your dataframe, read each formula in your dataframe.要写出你的 dataframe 中的所有公式,请阅读你的 dataframe 中的每个公式。
# replace the right side below with reading the formula from your dataframe
# e.g., formula_to_write = df.loc(...)`
rows = table.shape[0]
for row_num in range(1 + startrow, rows + startrow + 1):
formula_to_write = '=I{} * (1 - AM{})'.format(row_num+1, row_num+1)
worksheet.write_formula(row_num, col, formula_to_write)`
Later in the code (I seem to recall one of these might be redundant, but I haven't looked it up): writer.save() workbook.close()
稍后在代码中(我似乎记得其中一个可能是多余的,但我没有查过): writer.save() workbook.close()
writer = pd.ExcelWriter(FILE_PATH ,mode='a', if_sheet_exists='overlay')
col_Q_index = 3
best_formula = f'=max(L1,N98,Q{col_Q_index})'
formula_df = pd.DataFrame([[best_formula]])
formula_df.to_excel(writer, sheet_name=SHEET_NAME, startrow=i, startcol=17, index=False, header=False)
writer.save()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.