복붙노트

[PYTHON] 드라이브 API를 사용하여 Google 드라이브에서 빈 스프레드 시트 만들기

PYTHON

드라이브 API를 사용하여 Google 드라이브에서 빈 스프레드 시트 만들기

Google 드라이브에 빈 Google 시트 (메타 데이터로만 생성됨)를 만들고 싶습니다. Google SpreadSheet API 문서를 참조 할 때 DocumentsList API를 사용한다고했지만 대신 더 이상 사용되지 않으며 대신 Google 드라이브 API를 사용해달라고 요청합니다. 드라이브 API 문서에서 빈 시트를 만들 수있는 방법을 찾지 못했습니다. 누구든지이 작업을 수행하는 방법에 대한 단서가 있습니까?

해결법

  1. ==============================

    1.MIME 유형을 application / vnd.google-apps.spreadsheet로 설정하여 드라이브 API를 사용하여이 작업을 수행 할 수 있습니다.

    MIME 유형을 application / vnd.google-apps.spreadsheet로 설정하여 드라이브 API를 사용하여이 작업을 수행 할 수 있습니다.

    파이썬에서 이렇게하려면 :

    from apiclient.discovery import build
    service = build('drive', 'v2')
    
    import httplib2
    credentials = ... # Obtain OAuth 2.0 credentials
    http = credentials.authorize(httplib2.Http())
    
    body = {
      'mimeType': 'application/vnd.google-apps.spreadsheet',
      'title': 'Name of Spreadsheet',
    }
    file = service.files().insert(body=body).execute(http=http)
    # or for version 3 it would be
    # file = service.files().create(body=body).execute(http=http)
    

    Google API 탐색기로 가서 시도해보십시오!

  2. ==============================

    2.(2016 년 7 월) 위의 BossyLobster의 대답은 여전히 ​​유효합니다 (Drive API v2는 아직 지원되지 않습니다). 그러나 이해를 돕기 위해 같은 일을하는보다 현대적인 방법과 몇 가지 비디오가 아래에 나와 있습니다.

    (2016 년 7 월) 위의 BossyLobster의 대답은 여전히 ​​유효합니다 (Drive API v2는 아직 지원되지 않습니다). 그러나 이해를 돕기 위해 같은 일을하는보다 현대적인 방법과 몇 가지 비디오가 아래에 나와 있습니다.

    아래의 두 예제 모두에 대한 상용구 상용구

    from apiclient import discovery
    from httplib2 import Http
    from oauth2client import file, client, tools
    
    store = file.Storage('storage.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
        creds = tools.run_flow(flow, store)
    

    참고 : API 프로젝트 및 OAuth2 자격증 명을 만들고 해당 자격 증명을 client_secret.json (또는 client_id.json) 파일로 다운로드하려면 Google Developers Console로 이동하십시오.

    Google 드라이브 API v3 (& v2)이 포함 된 새 / 빈 시트 만들기

    # above: SCOPES = 'https://www.googleapis.com/auth/drive.file'
    DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))
    data = {
        'name': 'My new Sheet',
        'mimeType': 'application/vnd.google-apps.spreadsheet',
    }
    sheet = DRIVE.files().create(body=data).execute() # insert() for v2
    

    Google 스프레드 시트 API v4를 사용하여 새 / 빈 시트 만들기

    # above: SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
    SHEETS = discovery.build('sheets', 'v4', http=creds.authorize(Http()))
    data = {'properties': {'title': 'My new Sheet'}}
    sheet = SHEETS.spreadsheets().create(body=data).execute()
    

    이제 "왜 빈 시트를 만드는 두 가지 다른 방법이 있습니까?"라고 묻습니다. 간략하게 말하자면 Sheets API는 기본적으로 스프레드 시트 중심의 작업, 즉 데이터 삽입, 스프레드 시트 행 읽기, 셀 서식 지정, 차트 만들기, 피벗 테이블 추가 등을 의미하며 작성 / 삭제 및 가져 오기와 같은 파일 지향적 인 요청은 아닙니다. / export 드라이브 API가 올바른 사용법입니다. 그것은 단지 일이 그렇게 일어난다. 왜냐하면 창조는 일종의 양자 일 뿐이므로, 그것을하는 두 가지 방법이있다.

  3. ==============================

    3.스프레드 시트를 작성하기위한 api 참조는 https://developers.google.com/sheets/reference/rest/v4/spreadsheets/create에 있습니다.

    스프레드 시트를 작성하기위한 api 참조는 https://developers.google.com/sheets/reference/rest/v4/spreadsheets/create에 있습니다.

    새 스프레드 시트를 작성하는 코드 스 니펫은 다음과 같습니다.

    String[] SCOPES = { SheetsScopes.SPREADSHEETS };
    
    GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
            getApplicationContext(),
            Arrays.asList(SCOPES)).setBackOff(new ExponentialBackOff());
    credential.setSelectedAccountName("your_google_account@gmail.com");
    
    HttpTransport transport = AndroidHttp.newCompatibleTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    
    com.google.api.services.sheets.v4.Sheets service =
        new com.google.api.services.sheets.v4.Sheets.Builder(
            transport,
            jsonFactory,
            credential)
        .setApplicationName("Google Sheets API Android Quickstart")
        .build();
    
    Spreadsheet spreadsheet = new Spreadsheet();
    SpreadsheetProperties properties = new SpreadsheetProperties();
    properties.setTitle("SpreadSheetTitle");
    spreadsheet.setProperties(properties);
    
    service.spreadsheets().create(spreadsheet).execute()
    
  4. ==============================

    4.제안 된 방법은 나를 위해 작동하지 않았지만 다음 코드가 작동합니다.

    제안 된 방법은 나를 위해 작동하지 않았지만 다음 코드가 작동합니다.

    # requires: uid='example@gmail.com', pass1='password', 
    # name_spr='name_of_spreadsheet'
    
    import gdata.docs.client
    
    docs_client = gdata.docs.client.DocsClient()
    docs_client.ClientLogin(uid, pass1, 'any')
    document = gdata.docs.data.Resource(type='spreadsheet', title=name_spr)
    resource = docs_client.CreateResource(document)
    full_id = resource.resource_id.text # returned by gdata
    gs_id = full_id[len('spreadsheet:'):]
    
  5. ==============================

    5.당신은 또한 내가 썼던 pygsheets 라이브러리를 시험해 볼 수 있었다. 그것은 당연히 스프레드 시트를 만드는 것보다 많은 기능을 제공한다.

    당신은 또한 내가 썼던 pygsheets 라이브러리를 시험해 볼 수 있었다. 그것은 당연히 스프레드 시트를 만드는 것보다 많은 기능을 제공한다.

    import pygsheets
    
    gc = pygsheets.authorize(outh_file='client_secret.json')
    
    # Open spreadsheet and then worksheet
    gc.create('my new sheet')
    
  6. ==============================

    6.브라우저에서 직접 열 수는 없으므로 나머지 코드를 작성해야하는이 문제에 도움을주십시오.

    브라우저에서 직접 열 수는 없으므로 나머지 코드를 작성해야하는이 문제에 도움을주십시오.

    import gspread
    from oauth2client.service_account import ServiceAccountCredentials
    scope= ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
    credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json',scope)
    gc=gspread.authorize(credentials)
    sh=gc.create('NewOne')
    sh.share('manendra@shukla-217213.iam.gserviceaccount.com',perm_type='user',role='writer')
    worksheet=sh.add_worksheet(title="Mark",rows="100",cols="20")
    sh=gc.open('NewOne')
    worksheet=sh.get_worksheet(0)
    
  7. from https://stackoverflow.com/questions/12741303/creating-empty-spreadsheets-in-google-drive-using-drive-api by cc-by-sa and MIT license