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)
}
}
위 코드는 기존 시트에 값이 있으면 초기화 후
다시 새로운 값을 넣는 코드이다.
'Node.js' 카테고리의 다른 글
[Next.js] 멜론 차트 크롤링하기 (0) | 2024.01.11 |
---|---|
[Next.js] 멜론 아티스트 상세페이지 크롤링 (2) | 2024.01.09 |
[Node.js] 익스프레스 서버 구축 (0) | 2024.01.08 |