Using openpyxl to read file from memory

后端 未结 3 1210
情书的邮戳
情书的邮戳 2020-12-06 04:32

I downloaded a google-spreadsheet as an object in python.

How can I use openpyxl use the workbook without having it to save to disk first?

I know that xlrd c

相关标签:
3条回答
  • 2020-12-06 04:34

    Actually enough is to:

    file = open('path/to/file.xlsx', 'rb')
    wb = openpyxl.load_workbook(filename=file)
    

    and it will work. No need for BytesIO and stuff.

    0 讨论(0)
  • 2020-12-06 04:40

    I was looking to load a file from an URL and here is what I came up with:

    util:

    from openpyxl import load_workbook
    from io import BytesIO
    import urllib
    
    def load_workbook_from_url(url):
        file = urllib.request.urlopen(url).read()
        return load_workbook(filename = BytesIO(file))
    

    usage:

    import openpyxl_extended
    
    book = openpyxl_extended.load_workbook_from_url('https://storage.googleapis.com/pnbx-cdn/pen-campaign/campaigner-template-fr.xlsx')
    
    0 讨论(0)
  • 2020-12-06 04:57

    In the docs for load_workbook it says:

    #:param filename: the path to open or a file-like object
    

    ..so it was capable of it all the time. It reads a path or takes a file-like object. I only had to convert my file-like object returned by urlopen, to a bytestream with:

    from io import BytesIO
    wb = load_workbook(filename=BytesIO(input_excel.read()))
    

    and I can read every piece of data in my Google-spreadsheet.

    0 讨论(0)
提交回复
热议问题