필요한 도구
- Visaul Studio Code
- NodeJS
- Google Cloud Platform
- Google Drive
1. NodeJS 라이브러리
소개
https://www.npmjs.com/package/google-spreadsheet
google-spreadsheet
Google Sheets API (v4) -- simple interface to read/write data and manage sheets. Latest version: 3.3.0, last published: 2 months ago. Start using google-spreadsheet in your project by running `npm i google-spreadsheet`. There are 307 other projects in the
www.npmjs.com
npm i google-spreadsheet
안에 들여다보시면 Google API Sheet 사용할 수 있도록 기본 코드가 알려줍니다.
const { GoogleSpreadsheet } = require('google-spreadsheet');
// Initialize the sheet - doc ID is the long id in the sheets URL
const doc = new GoogleSpreadsheet('<the sheet ID from the url>');
// Initialize Auth - see https://theoephraim.github.io/node-google-spreadsheet/#/getting-started/authentication
await doc.useServiceAccountAuth({
// env var values are copied from service account credentials generated by google
// see "Authentication" section in docs for more info
client_email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
private_key: process.env.GOOGLE_PRIVATE_KEY,
});
await doc.loadInfo(); // loads document properties and worksheets
console.log(doc.title);
await doc.updateProperties({ title: 'renamed doc' });
const sheet = doc.sheetsByIndex[0]; // or use doc.sheetsById[id] or doc.sheetsByTitle[title]
console.log(sheet.title);
console.log(sheet.rowCount);
// adding / removing sheets
const newSheet = await doc.addSheet({ title: 'hot new sheet!' });
await newSheet.delete();
이 코드를 구동시키기 위해 필요한 정보는
'<the sheet ID from the url>', GOOGLE_SERVICE_ACCOUNT_EMAIL, GOOGLE_PRIVATE_KEY
3개의 정보가 필요합니다.
1. <the sheet ID from the url>' 얻는 방법 (Google Drive)
생성한 스프레드 시트의 ID 얻기
Google Drive에 스프레드시트 파일을 만드시고
주소에 https://docs.google.com/spreadsheets/d /[복사해야할 Sheet ID]/edit#gid=0 입니다.
첫 번째 데이터를 구했네요
2. JSON 파일에서 필요한 키 정보 얻기
GOOGLE_SERVICE_ACCOUNT_EMAIL, GOOGLE_PRIVATE_KEY 얻는 방법 (GCP)
이 데이터를 얻기 위해서는 GCP로 가야합니다.
https://console.cloud.google.com/
Google 클라우드 플랫폼
로그인 Google 클라우드 플랫폼으로 이동
accounts.google.com
새 프로젝트를 만들어 주세요
만들고 API 및 서비스에 들어갑니다.
사용자 인증정보 > 사용자 인증 정보 만들기 > 서비스 계정 클릭합니다.
서비스 계정 이름에 원하는 이름을 작성합니다.
그리고 완료를 눌러주세요
서비스 계정이 정상적으로 만들어 졌죠?
GOOGLE_SERVICE_ACCOUNT_EMAIL 를 얻게 되었네요
하지만 더 진행해야합니다.
저 이메일을 클릭하시고
상 메뉴 에서 키 > 키 추가 > 새 키 만들기를 눌러시고 키 유형을 JSON으로 받아주세요
아래와 같은 정보가 담겼을 꺼에요.
{
"type": "service_account",
"project_id": "[프로젝트 아이디]",
"private_key_id": "[해시한 키]",
"private_key": "-----BEGIN PRIVATE KEY-----\개인 키\n-----END PRIVATE KEY-----\n",
"client_email": "임시 아이디@[프로젝트 아이디].iam.gserviceaccount.com",
"client_id": "숫자",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "제품 url"
}
위에 정보에서 GOOGLE_SERVICE_ACCOUNT_EMAIL(client_email)를 복사하여 사용하려는 스프레드 시트에 추가합니다.
권한도 편집자로 변경해주세요.
다운로드한 JSON credientials.json으로 파일 명칭을 변경해서 사용할 수 있습니다.
const { GoogleSpreadsheet } = require('google-spreadsheet');
const doc = new GoogleSpreadsheet('스트레드 시트 ID ');
const credentials = require('./credentials.json');
async function Run() {
await doc.useServiceAccountAuth(credentials);
await doc.loadInfo();
await doc.updateProperties({title: 'APITest'}); //스트레드 시트 제목 변경
console.log(doc.title);
const sheet1 = doc.sheetsByIndex[0]; // WorkSheet 선택
const result = await sheet1.getRows();
console.log(result);
}
Run();