Node.js

Google Spreadsheet API 사용하기

이경욱 2024. 1. 8. 18:49

1. 구글 클라우드 콘솔에서 프로젝트를 생성

2. API 및 서비스 탭 이동

3. 라이브러리에서 Google Sheet API 를 사용하도록 설정

4. 사용자 인증 정보에서 서비스 계정 생성

 

서비스 계정을 생성하면 key값이 담긴 JSON 파일을 주는데, 

이걸 import 해서 사용하면 된다.

 

import axios from 'axios'
import { GoogleSpreadsheet } from "google-spreadsheet";
import { JWT } from "google-auth-library";
import credential from "../../../key.json"

    const SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
    const GOOGLE_SHEET_ID = '본인 시트 ID'

    const jwt = new JWT({
        project_id: credential.project_id,
        keyId: credential.private_key_id,
        key: credential.private_key,
        email: credential.client_email,
        clientId: credential.client_id,
        scopes: SCOPES,
    })

 

 

이렇게 세팅이 됐으면

이제 doc 변수를 사용하여 CRUD가 가능하다.

 

    const loadGoogleDoc = async () => {
        try {
            const doc = new GoogleSpreadsheet(GOOGLE_SHEET_ID, jwt)
            await doc.loadInfo();
            const sheet = doc.sheetsById[0]
            const rows = await sheet.getRows()
            return rows;

        } catch (err) {
            console.error("Sheet Load Rows Error:", err)
        }
    }

 

 

위 코드는 모든 Row를 읽어오는 것

 

 

    const addGoogleDoc = async () => {
        try {
            const doc = new GoogleSpreadsheet(GOOGLE_SHEET_ID, jwt)
            await doc.loadInfo();
            const sheet = await doc.sheetsByTitle['Chart']
            const data: any = await getHtml()
            const rows = await sheet.getRows()
            if (rows) {
                sheet.clearRows()
                sheet.addRows(data)
            } else {
                sheet.addRows(data)
            }
        } catch (err) {
            console.error("Sheet Load Rows Error:", err)
        }
    }

 

위 코드는 기존 시트에 값이 있으면 초기화 후

다시 새로운 값을 넣는 코드이다.