WolVes
WolVes

Reputation: 1336

Python dataframe illegal character error into 'ascii' codec decode error

I am attempting to write a pandas dataframe to excel. Initially, I received

openpyxl.utils.exceptions.IllegalCharacterError

which I resolved with:

def export_file(clients):

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

    clients.to_excel('all_clients.xlsx')

    return()

Which then resulted in:

 UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 17: ordinal not in range(128)

However, if i resolve the unicode error I get the initial pyxl error.

I seem to be unable to resolve one error without getting the opposing error. Any suggestions?

Upvotes: 1

Views: 5204

Answers (1)

Apsara Vidhya
Apsara Vidhya

Reputation: 71

Instead of writing directly using pandas, user xlsxwrite engine. This will resolve the errors.

writer = pd.ExcelWriter('all_clients.xlsx', engine='xlsxwriter') # engine is set here
clients.to_excel(writer,'Sheet1') # it is called here to write the excel sheet

openpyxl.utils.exceptions.IllegalCharacterError will be resolved.

Upvotes: 4

Related Questions