使用python向excel添加新列表时的UnicodeDecodeError

时间:2016-06-30 13:06:45

标签: python excel pandas openpyxl

我尝试使用

将新工作表添加到Excel文件中
def add_xlsx_sheet(df, sheet_name=u'Десктопы кратко', index=True, digits=2, path=None):
book = load_workbook(path)
writer = pd.ExcelWriter(path, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
if sheet_name in list(writer.sheets.keys()):
    sh = book.get_sheet_by_name(sheet_name)
    book.remove_sheet(sh)
df.to_excel(excel_writer=writer, sheet_name=sheet_name, startrow=0, startcol=0,
            float_format='%.{}f'.format(digits), index=index)
pd.DataFrame({}).to_excel(writer, sheet_name=u'Смартфоны кратко')
pd.DataFrame({}).to_excel(writer, sheet_name=u'Смартфоны полно')
writer.save()

df.groupby('member_id').apply(lambda x: add_xlsx_sheet(x, u'Десктопы полно', path='{}.xlsx'.format(x.name)))

并收到错误

Traceback (most recent call last):
  File "C:/Users/�����/PycharmProjects/14-27/desktop.py", line 142, in <module>
df.groupby('member_id').apply(lambda x: add_xlsx_sheet(x, u'Десктопы полно'.decode('utf-8'), path='{}.xlsx'.format(x.name)))
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc4 in position 0: invalid continuation byte

我之前问了这个问题,但没有解决。我尝试用'Десктопы полно'.decode('utf-8')检查它,但它没有帮助。

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

df.groupby('member_id').apply(lambda x: add_xlsx_sheet(x, u'Десктопы полно', path='u{}.xlsx'.format(x.name)))

如果这不起作用,您可能需要解码x.name。或者切换到Python 3。