Skip to content

Instantly share code, notes, and snippets.

@iketiunn
Last active November 21, 2019 04:27
Show Gist options
  • Save iketiunn/6359cd67233cd35707868fde2e66f335 to your computer and use it in GitHub Desktop.
Save iketiunn/6359cd67233cd35707868fde2e66f335 to your computer and use it in GitHub Desktop.
(TBD) spreadsheet api example
/**
* After aquired a service account's certfication with right permisstion with spreadsheet
*/
import { google } from "googleapis"; // npm i googleapis
const serviceAccount = require('service-account-cert.json')
const auth = new google.auth.JWT(
serviceAccount.client_email,
undefined,
serviceAccount.private_key,
"https://www.googleapis.com/auth/spreadsheets",
undefined
);
const sheets = google.sheets("v4");
const spreadsheetId = "example"
async function createSheet(title) {
const spreadsheet = await sheets.spreadsheets.get({
auth,
spreadsheetId,
includeGridData: true
});
if (!spreadsheet.data.sheets) {
throw new Error("Sheets not found!");
}
const targetSheet = spreadsheet.data.sheets.find(
s => s.properties && s.properties.title === title
);
if (!targetSheet) {
await sheets.spreadsheets.batchUpdate({
auth,
spreadsheetId,
requestBody: {
requests: [{ addSheet: { properties: { title } } }]
}
});
console.log(`Create sheet: ${title}`);
}
}
async function updateSheet(title: string) {
const values = [[new Date()]];
const updateResult = await sheets.spreadsheets.values.update({
auth,
spreadsheetId,
range: `${title}`, // or ${title}`A1!
valueInputOption: "USER_ENTERED",
requestBody: {
majorDimension: "ROWS",
values
}
});
if (updateResult.status === 200) {
console.log("Update success" );
} else {
console.error(updateResult.data);
console.error("Update failed");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment