Search code examples
javascriptnode.jsgoogle-sheetsgoogle-sheets-apigoogle-api-nodejs-client

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.

Opening spreadsheet by name in IFTTT


Solution

  • 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}`)
            })
        }
    });