Google Drive API (Javascript)を使ってSpreadsheetの内容をCSVで取得する
Google Drive APIだけで行けるかと思ったら無理っぽくて、色々解らなかったのでメモ。
Google APIs ConsoleのServicesからDrive APIをOnにする。
API Accessで
"Client ID(for web applications)"と"Bowser Key"を作る。
"Client ID"の"JavaScript origins"はとりあえず"http://localhost"でいい感じ。
で、こんな感じのコードでできた。
<!DOCTYPE HTML> <html lang="ja"> <head> <meta charset="utf-8"> <title>Export Spreadsheet from Google Drive</title> <script type="text/javascript"> var clientId = '<YOUR_CLIENT_ID>'; var apiKey = '<YOUR_API_KEY>'; var scopes = 'https://www.googleapis.com/auth/drive'; function handleClientLoad() { gapi.client.setApiKey(apiKey); window.setTimeout(checkAuth,1); } function checkAuth() { gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult); } function handleAuthResult(authResult) { if (authResult && !authResult.error) { makeApiCall(); } else { gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult); } } function makeApiCall() { var accessToken = gapi.auth.getToken().access_token; var xhr = new XMLHttpRequest(); var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=<SPREADSHEET_KEY>&exportFormat=csv"; xhr.open('GET', url); xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken); xhr.onload = function() { console.log(xhr.responseText); }; xhr.onerror = function() { console.log("error"); }; xhr.send(); } </script> <script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script> </head> <body> </body> </html>