T
T
Tayrus02020-11-19 13:18:28
Python
Tayrus0, 2020-11-19 13:18:28

Why does bytesIO break pandas generated xlsx file?

There is such a code

df = pandas.DataFrame()
    bb = BytesIO()
    bb.name = f'test.xlsx'
    bb.encoding = "utf-8"

    to_add = {'1': one,
              '2': one,
              '3': one,
              '4': one,
              '5': one,
              '6': one,
              '7': one}
    df = df.append(to_add, ignore_index=True)
    df.to_excel(bb, index=False)

    bb.seek(0)

    await bot.send_document(message.chat.id, bb)


It creates an excel file (xlsx), everything is created successfully, but when I open the file it says that it is damaged, how can I fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Mirilaczvili, 2020-11-19
@2ord

Try with argument keys

await bot.send_document(chat_id=message.chat.id, document=bb)

This is how a correct XLSX file is written:
the code
import pandas
from io import BytesIO

one = 'ttt'
to_add = {'1': one,
          '2': one,
          '3': one,
          '4': one,
          '5': one,
          '6': one,
          '7': one}

bb = BytesIO()
bb.name = f'test.xlsx'
bb.encoding = "utf-8"

df = pandas.DataFrame()
df = df.append(to_add, ignore_index=True)
print(df)

df.to_excel(bb, index=False)

with open(bb.name, 'wb') as f:
    f.write(bb.getbuffer())

Add. info:
https://python-telegram-bot.readthedocs.io/en/stab...
https://gist.github.com/ohld/9c9cbcfa09020be62a635...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question