2013-12-17 6 views
11

Google 스프레드 시트를 Python으로 객체로 다운로드했습니다.openpyxl을 사용하여 메모리에서 파일 읽기

openpyxl을 사용하여 먼저 통합 문서를 디스크에 저장하지 않고 사용할 수 있습니까?

내가 xlrd에 의해이 작업을 수행 할 수 있다는 사실을 알고 "downloaded_spreadsheet"와

book = xlrd.open_workbook(file_contents=downloaded_spreadsheet.read()) 

을 대상으로 내 다운로드 XLSX 파일 인.

xlrd 대신 xlsx-support (read) 때문에 openpyxl을 사용하고 싶습니다.

나는

#!/usr/bin/python 

    import openpyxl 
    import xlrd 
    # which to use..? 


import re, urllib, urllib2 

class Spreadsheet(object): 
    def __init__(self, key): 
     super(Spreadsheet, self).__init__() 
     self.key = key 

class Client(object): 
    def __init__(self, email, password): 
     super(Client, self).__init__() 
     self.email = email 
     self.password = password 

    def _get_auth_token(self, email, password, source, service): 
     url = "https://www.google.com/accounts/ClientLogin" 
     params = { 
     "Email": email, "Passwd": password, 
     "service": service, 
     "accountType": "HOSTED_OR_GOOGLE", 
     "source": source 
     } 
     req = urllib2.Request(url, urllib.urlencode(params)) 
     return re.findall(r"Auth=(.*)", urllib2.urlopen(req).read())[0] 

    def get_auth_token(self): 
     source = type(self).__name__ 
     return self._get_auth_token(self.email, self.password, source, service="wise") 

    def download(self, spreadsheet, gid=0, format="xls"): 

     url_format = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=%s&exportFormat=%s&gid=%i" 
     headers = { 
     "Authorization": "GoogleLogin auth=" + self.get_auth_token(), 
     "GData-Version": "3.0" 
     } 
     req = urllib2.Request(url_format % (spreadsheet.key, format, gid), headers=headers) 
     return urllib2.urlopen(req) 

if __name__ == "__main__": 



    email = "[email protected]" # (your email here) 
    password = '.....' 
    spreadsheet_id = "......" # (spreadsheet id here) 

    # Create client and spreadsheet objects 
    gs = Client(email, password) 
    ss = Spreadsheet(spreadsheet_id) 

    # Request a file-like object containing the spreadsheet's contents 
    downloaded_spreadsheet = gs.download(ss) 


    # book = xlrd.open_workbook(file_contents=downloaded_spreadsheet.read(), formatting_info=True) 

    #It works.. alas xlrd doesn't support the xlsx-funcionality that i want... 
    #i.e. being able to read the cell-colordata.. 

은 내가 구글 - 스프레드 시트에 주어진 셀의 색상 데이터를 얻을 수 개월 동안 사투를 벌인거야 때문에 누군가가 도움을 수 있기를 바랍니다 ... 지금까지 사용하고 있습니다. (나는 그것을 지원하지 않는 구글-API를 알고 ..)는 말한다 load_workbook에 대한 문서에서

답변

21

:

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

것은 그것이 항상 그것을 할 수 있었다 ..so. 경로를 읽거나 파일과 같은 객체를 가져옵니다. 난 단지와 bytestream에, urlopen로 내 파일 - 류의 객체가 반환 변환했다 :

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

나는 내 구글 스프레드 시트에서 데이터의 모든 조각을 읽을 수 있습니다.

+0

+1 - 비슷한 오류가 발생했습니다. 나는 전반부 만 읽고 파일을 읽을 수 있다고 생각했습니다. 이제 돌아가서 완전히 읽었고 파일과 유사한 객체를 처리 할 수 ​​있음을 알았습니다. –

1

사실은 충분히하는 것입니다

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

그것은 작동합니다. BytesIO와 같은 것들이 필요 없습니다.

+1

질문에서 알 수 있듯이 파일 시스템에서 읽지 않습니다. 그것은 스트림입니다. –

관련 문제