How to read a spreadsheet using Google Sheets API + Javascript

≡放荡痞女 提交于 2019-12-25 18:36:26

问题


There's a nice solution to updating Google spreadsheets using the Drive REST API in this question.

It overwrites the current contents. I'd like to read in the current contents, modify them, then update.

How do I read in the current spreadsheet?


回答1:


This works (assuming your credentials are in order and you are authorized):

function getFileInfo(fileId, callback) {
    try {
        gapi.client.drive.files.get({
            fileId: fileId,
            fields: "appProperties,capabilities,contentHints,createdTime,description,explicitlyTrashed,fileExtension,folderColorRgb,fullFileExtension,headRevisionId,iconLink,id,imageMediaMetadata,isAppAuthorized,kind,lastModifyingUser,md5Checksum,mimeType,modifiedByMeTime,modifiedTime,name,originalFilename,ownedByMe,owners,parents,permissions,properties,quotaBytesUsed,shared,sharedWithMeTime,sharingUser,size,spaces,starred,thumbnailLink,trashed,version,videoMediaMetadata,viewedByMe,viewedByMeTime,viewersCanCopyContent,webContentLink,webViewLink,writersCanShare",
        }).then(function(response) {
            info = JSON.parse(response.body);
            callback(info);
        })
    } catch (err) {
        console.log('Something bad happened: ' + err);
    }
}

It returns all the known metadata fields (as of this time). You'll want to trim back the list to those you need. But it does not return the actual spreadsheet contents. For that, you'll need to use the export api:

function getSpreadsheet(fileId, callback) {
    var spreadsheet;
    try {
        gapi.client.drive.files.export({
            fileId: fileId,
            mimeType: 'text/csv'
        }).then(function(response) {
            spreadsheet = Papa.parse(response.body).data;
            callback(spreadsheet);
        })
    } catch (err) {
        console.log('Something bad happened: ' + err);
    }
}

The data is return as a csv string. We use Papa.parse to turn it into a 2D array.



来源:https://stackoverflow.com/questions/37264159/how-to-read-a-spreadsheet-using-google-sheets-api-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!