简体   繁体   中英

Open spreadsheet by name or create new spreadsheet if none is found

I'm using the Google sheets API and Nodejs to append values to a spreadsheet. However, i would like to get the spreadsheet ID by the spreadsheet's name, or create a new spreadsheet if none is found. To be clear, what i mean is what IFTTT does with it's Append to Spreadsheet action. I cannot know the spreadsheet ID beforehand.

在IFTTT中按名称打开电子表格

Assuming you already know how to authenticate with googleapis , here is a minimal example how to query the Drive API to search for spreadsheets with a specific name and using the Sheets API to create if there is none.

// auth is google.auth.OAuth2()
const sheets = google.sheets({version: 'v4', auth})
const drive = google.drive({version: 'v3', auth})

var fileName = 'yourSpreadSheetName'
var mimeType = 'application/vnd.google-apps.spreadsheet'

drive.files.list({
    q: `mimeType='${mimeType}' and name='${fileName}'`,
    fields: 'files(id, name)'
}, (err, res) => {
    if (err) return console.log('drive files error: ' + err)
    const files = res.data.files
    if (files.length) {

        // There is an existing spreadsheet(s) with the same filename
        // The spreadsheet Id will be in files[x].id
        console.log(`found spreadsheet with id: ${files[0].id}`)

    } else {

        // Create spreadsheet with filename ${fileName}
        sheets.spreadsheets.create({
            resource: {
                properties: { title: fileName }},
            fields: 'spreadsheetId'
        }, (err, spreadsheet) => {
            if (err) return console.log('spreadsheets create error: ' + err)
            // The spreadsheet Id will be in ${spreadsheet.data.spreadsheetId}
            console.log(`created spreadsheet with id: ${spreadsheet.data.spreadsheetId}`)
        })
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM