Writing dataframes to multiple sheets in existing Excel file. Get 'We Found Problem with some content in X.xlsx' when opening excel file

霸气de小男生 提交于 2020-12-13 04:25:38

问题


I'm creating a few dfs based on existing excel files. I'm then writing each of those dfs to their own separate sheet in a different (existing excel) file. Script executes fine, but when I open the excel file the dfs were written to I get the following error msg: "We found a problem with some content in 'X.xlsx'...

I tried this not using openpyxl as several answers on similar posts indicated you didn't have to use openpyxl; however, pandas docs indicate you need to use openpyxl if writing to .xlsx.

import pandas as pd
from openpyxl import load_workbook

df_complete = pd.read_excel('completed_contracts_2019.xlsx', 
index_col=None)
df_wip_out = pd.read_excel('wip19.xlsx', index_col=None)
df_in = pd.read_excel('wip_18_to_19.xlsx', index_col=None)

with pd.ExcelWriter('Final_Template.xlsx', engine='openpyxl') as writer:
    writer.book = load_workbook('Final_Template.xlsx')
    df_complete.to_excel(writer, sheet_name='complete', index=False)
    df_wip_out.to_excel(writer, sheet_name='wipout', index=False)
    df_in.to_excel(writer, sheet_name='wipin', index=False)

I expect to open the excel file without getting the error.


回答1:


Hit the same issue with openpyxl, but actually it might not be the problem of openpyxl.

Based on my experience, after I got a pop window with "Alert We found a problem with some content in......". Just look into what was the error, and finally found that, in Excel if the data format is "General", you cannot input the string starts with "==", otherwise Excel will deem it as a syntax error. But if the data format is "Text", there will be no problem.

Two solution: 1) If you are sure some of the string starts with "==", and it is not that necessary in your case, you might have to change the first "=" or insert another character at the beginning. Then write it into xls file with openpyxl. This is what I applied. 2) Or you may use openpyxl set the data format of cell (might be "number_format") as "Text". I didn't successfully try this way, because after manually setting a cell data format as "Text", read its "number_format" with openpyxl, got the value of "@"(not "Text"). But when I set "number_format" to "@" with openpyxl, then wrote "==" into it, it still hit the issue.

Besides "==", not sure if any other string will also be deemed as a syntax error by Excel. Anyway, if you happen to hit the issue due to "==", you can try the first solution as a workaround.



来源:https://stackoverflow.com/questions/57982349/writing-dataframes-to-multiple-sheets-in-existing-excel-file-get-we-found-prob

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!