简体   繁体   English

将带有公式的 Pandas DataFrame 保存到 xlsx 文件

[英]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:

LibreOffice 中的示例输出

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()

Documentation is here .文档在这里

  • you need to save in as usual just keep in mind to write the formula as string.您需要像往常一样保存,请记住将公式写为字符串。
  • you can use also f strings with vars.您也可以将 f 字符串与 vars 一起使用。
    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.

相关问题 Pandas:将多个DataFrame导出到多个xlsx文件 - Pandas: Exporting multiple DataFrames to multiple xlsx files 阅读文件夹中的所有xlsx文件,并将文件保存在不同的DataFrame中 - Read all xlsx-Files in a folder and save the files in different DataFrames 蟒蛇+熊猫; 如何正确合并数据帧列表的字典并保存到 xlsx 或 csv 作为单个表 - Python+Pandas; How to proper merge a dictionary of lists of dataframes and save to xlsx or csv as single table .xlsx文件与熊猫合并时出现问题 - Trouble merging .xlsx files with pandas 如何将熊猫数据框从 praw 保存到 xlsx? - How to save pandas dataframe from praw to xlsx? 将 XML 文件解析为 Pandas 数据帧 - Parsing XML files into Pandas dataframes 如何将多个 Pandas 数据帧写入 Excel? (当前方法 Corrupts.xlsx) - How to Write Multiple Pandas Dataframes to Excel? (Current Method Corrupts .xlsx) 自动将多个json文件(具有不同的信息)读取并保存到不同的pandas数据帧 - Automate the read and save of several json files (with different information) to different pandas dataframes 使用熊猫将数日长的数据框拆分为半小时的数据框,并将其另存为csv文件 - Splitting several days long dataframe into half-hourly dataframes using pandas and save them as csv-files 保存大xlsx文件熊猫python - Saving big xlsx files pandas python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM