1

Sorry for my english. I try create new file in google drive(xlsx) and set someting data. But i have error:

AttributeError: 'bytes' object has no attribute 'encode'

my code:

    drive = DriveBox() # return pydrive obj

    df = pd.DataFrame({'a': [1, 2], 'b': [2, 3]})
    wb = Workbook()
    writer = pd.ExcelWriter('', engine='openpyxl')
    writer.book = wb
    df.to_excel(writer)

    xmls = drive.g_drive.CreateFile({'title': 'test.xlsx',
                                     'mimeType': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
    xmls.SetContentString(save_virtual_workbook(wb))
    xmls.Upload()

UPD:

python vers: 3,6 traceback:

C:\Python36\python.exe C:/work/projects/project/do_api/Main.py
Main
Traceback (most recent call last):
  File "C:/work/projects/project/do_api/Main.py", line 18, in <module>
    class Main:
  File "C:/work/projects/project/do_api/Main.py", line 36, in Main
    xmls.log()
  File "C:\work\projects\project\do_api\xmsl\XmslBox.py", line 80, in log
    xmls.SetContentString(save_virtual_workbook(wb))
  File "C:\Python36\lib\site-packages\pydrive\files.py", line 155, in SetContentString
    self.content = io.BytesIO(content.encode(encoding))
AttributeError: 'bytes' object has no attribute 'encode'
r1299597
  • 609
  • 3
  • 10
  • 20
  • 1
    traceback & python version please – Jean-François Fabre Jan 25 '18 at 20:32
  • @Jean-FrançoisFabre i upd question – r1299597 Jan 25 '18 at 20:39
  • 1
    `xmls.SetContentString` doesn't work for binary strings. Have you tried `xmls.SetContent` instead? which methods are available starting with `SetContent` – Jean-François Fabre Jan 25 '18 at 20:43
  • 1
    what is `save_virtual_workbook` ? a function of yours? – Jean-François Fabre Jan 25 '18 at 20:47
  • @Jean-FrançoisFabre `save_virtual_workbook` it form `from openpyxl.writer.excel import save_virtual_workbook` . `xmls` it `GoogleDriveFile` it doesnt have attribute 'SetContent' – r1299597 Jan 25 '18 at 20:50
  • 1
    a workaround would be to create a temp file and to use `SetContentFile` with the filename. – Jean-François Fabre Jan 25 '18 at 20:51
  • To add some details on `SetContentFile`, you might want to check the [Create Spreadsheet from csv](https://github.com/googledrive/PyDrive/issues/84) a reported issue on PyDrive on how to create a file and uploading it using `drive.CreateFile()`. Hope this helps. – Mr.Rebot Jan 26 '18 at 14:33
  • I get an "AttributeError: 'bytes' object has no attribute 'encode'" error if I do uploaded.SetContentString(save_virtual_workbook(wb)), too? Any idea? – Tobi Apr 18 '20 at 17:48
  • 1
    I recently faced with almost the same problem and solved it with setting `file_to_upload.content=` (instead of `SetContentFile` or similar) and then `file_to_upload.Upload()`. I can't say exactly how good this solution is, but it works for me. – Timofey Katalnikov Apr 22 '21 at 21:52

0 Answers0