서버/Express

ExpressJS Google Spreadsheet API

realtrynna 2023. 1. 6. 21:22

ExpressJS Google Spreadsheet API

API 사용 전 GCP에 프로젝트와 사용자(IAM)를 생성해야 한다.

생성 방법은 이미 여러 사이트에 나와있으므로 생략한다.

 

 

  • 설치
npm i google-spreadsheeet

 

 

  • Instance 생성
    인수로 스프레드시트의 아이디를 넣어준다. (Sheet의 고유값을 의미)

const doc = new GoogleSpreadsheet(process.env.GOOGLE_SPREADSHEET_ID);

 

 

  • 사용자 Authentication
    useServiceAccountAuth 메서드는 객체를 인수로 받으며 사용자 정보가 들어간다.
    여기서 사용자 정보는 프로젝트명-""-"".json 파일에 데이터를 의미한다. 
    사용자 인증과 사용자 로드 동작의 결과값이 undefined는 정상을 의미한다.
const privateKey = process.env.GOOGLE_PRIVATE_KEY.split(String.raw`\n`).join('\n');

const authenticated = await doc.useServiceAccountAuth({
    client_email: process.env.GOOGLE_CLIENT_EMAIL,
    private_key: privateKey,
});

const accountLoader = await doc.loadInfo();

console.log(authenticated, accountLoader); // undefined undefined

 

 

  • Sheet 읽기
    시트는 Array 형태로 돼있으며 sheetsByIndex 메서드를 사용하며 구분한다.
const sheet = doc.sheetsByIndex;

console.log(sheet);

 

 

 

  • Row 읽기
    getRows 메서드를 사용하고 기본적으로 모든 Row를 가져온다.
    인수로 객체에 offset, limit을 넣으면 Pagination이 가능하다.
const sheet = doc.sheetsByIndex[0];
const rows = await sheet.getRows();

// 또는

const rowsPagination = await sheet.getRows({
    offset: 0,
    limit: 10,
});

console.log(rows, rowsPagination);

 

 

  • Row 쓰기
    Row를 쓰기 전 loadCells 메서드로 Sheet에 Cell들을 불러온다.
    Default는 모든 Cell을 Load 하고 인수로 Load 할 Cell의 Range를 설정할 수 있다.
    모든 Cell과 1천 개의 Cell을 Load 하는 시간 차이는 있었지만 근소하므로 Default로 설정한다.
const sheet = doc.sheetsByIndex[0];

await sheet.loadCells();

// 또는 

await sheet.loadCells("A1:D1001");

 

 

  • Row 쓰기 2
    다음은 1천 개의 더미 데이터를 Write 하는 코드다. getCellByA1 메서드로 데이터를 삽입할 Cell의 위치를 지정한다.
    id Column은 1이므로 i = 0이면 처음으로 삽입해야 할 Cell의 위치는 A2로 설정 돼야한다.

    반복문을 통해 Cell의 값을 넣은 후 최종적으로 saveUpdatedCells 메서드를 통해 입력된 값들을 최종적으로 업데이트  해야한다.
const sheet = doc.sheetsByIndex[0];

await sheet.loadCells();

for (let i = 0; i < 1000; i++) {
    const id = sheet.getCellByA1(`A${i + 2}`);
    const email = sheet.getCellByA1(`B${i + 2}`);
    const nickname = sheet.getCellByA1(`C${i + 2}`);
    const password = sheet.getCellByA1(`D${i + 2}`);

    id.value = faker.datatype.uuid();
    email.value = faker.internet.email();
    nickname.value = faker.internet.userName();
    password.value = faker.internet.password();
}

await sheet.saveUpdatedCells();

 

 

참고

https://developers.google.com/sheets/api/guides/concepts

'서버 > Express' 카테고리의 다른 글

ExpressJS typedi  (0) 2022.11.01
ExpressJS sharp  (0) 2022.10.08
ExpressJS Jest ES6 import export  (0) 2022.08.10
ExpressJS express-validator 유효성 검사  (0) 2022.06.23
ExpressJS nodemailer 비밀번호 초기화  (0) 2022.06.21