简体   繁体   中英

How to get sheetId with Google Sheets API in Javascript?

Hi if you want to use sortRange in Google Sheets API you need a sheetId as an int not string. How can I get it starting with the sheets name as string

This works perfectly to sort my the sheet. But sheetId I had to set manually. sheetId: 959061457

try {
    const request = {
        spreadsheetId: spreadsheetId,
        resource: {
            requests: [{
                sortRange: {
                    range: {
                        sheetId: 959061457,
                        startRowIndex: 1,
                        endRowIndex: 1000,
                        startColumnIndex: 0,
                        endColumnIndex: 6
                    },
                    sortSpecs: [{
                        sortOrder: 'DESCENDING',
                        dimensionIndex: 2
                    }]
                }
            }],
        },
        auth: client,
    };

    await sheets.spreadsheets.batchUpdate(request)
} catch (error) {
    console.log(error)
}

Is there an option to get sheetId as a number from some api? It's in the URL but sadly batchUpdate, clear or append do not have it as an int in the response

I have the spreadsheet ID and the table name as sting.

It works with https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/get

sheetname is the title of the sheet as a string

//Get sheetId by name
try {
    const request = {
        spreadsheetId: spreadsheetId,
        ranges: [sheetname],
        includeGridData: false,  
        auth: client,
    };

    res = await sheets.spreadsheets.get(request)
} catch (error) {
    console.log("Error get sheetId")
}

console.log(res.data.sheets[0].properties.sheetId)

You can use the getSheetid method. This will return the id of the sheet as a string:

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

Logger.log(sheet.getSheetId());

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