How to remove illegal characters so a dataframe can write to Excel

前端 未结 7 868
广开言路
广开言路 2020-12-03 05:14

I am trying to write a dataframe to an Excel spreadsheet using ExcelWriter, but it keeps returning an error:

openpyxl.utils.exceptions.IllegalCharacterError
         


        
7条回答
  •  执笔经年
    2020-12-03 05:22

    Based on Haipeng Su's answer, I added a function that does this:

    dataframe = dataframe.applymap(lambda x: x.encode('unicode_escape').
                     decode('utf-8') if isinstance(x, str) else x)
    

    Basically, it escapes the unicode characters if they exist. It worked and I can now write to Excel spreadsheets again!

提交回复
热议问题