Node.js는 Google 시트에 데이터를 씁니다.
어제 우리는 reading data from a Google sheet을 살펴보았습니다.
오늘 우리는 한 단계 더 나아가 실제로 시트에 데이터를 쓸 것입니다.
처음에는 동일한 스크립트를 사용합니다.
따라서 인증에 대한 시작 설명을 찾고 있다면 reading google sheet in node.js 문서를 참조하십시오.
오늘의 연습은 다음과 같이 진행됩니다.
![](https://s1.md5.ltd/image/d41d8cd98f00b204e9800998ecf8427e.gif)
Node.js Google 시트에 데이터 쓰기
우선, 쓰기만 가능하도록 초기 앱 설정이 있었으므로 새 권한을 부여해야 합니다.
변화
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
Google 시트 API 전체를 반영하기 위해
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
Note: We can't use Google's own sheet, so copy the sheet to your own version.
token.json
가 이미 있는 경우 이를 제거하고 node .
명령을 다시 실행하여 새 항목을 가져옵니다.이제
credentials.json
파일을 읽은 후 수행하는 작업을 변경해 보겠습니다.listMajors
함수를 호출했으므로 이제 writeData
로 변경하겠습니다.이제 함수는 다음과 같이 표시됩니다.
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
authorize(JSON.parse(content), writeData);
});
좋습니다. 이제 계속해서 이
writeData
함수를 생성할 수 있습니다.function writeData(auth) {
const sheets = google.sheets({ version: 'v4', auth });
let values = [
[
'Chris',
'Male',
'1. Freshman',
'FL',
'Art',
'Baseball'
],
// Potential next row
];
const resource = {
values,
};
sheets.spreadsheets.values.append({
spreadsheetId: '1XnbJ5JHeJS2KsTzz6wXtwASb5mkwkICn_XP_pDJIyTA',
range: 'Class Data!A1',
valueInputOption: 'RAW',
resource: resource,
}, (err, result) => {
if (err) {
// Handle error
console.log(err);
} else {
console.log('%d cells updated on range: %s', result.data.updates.updatedCells, result.data.updates.updatedRange);
}
});
}
새 시트 API 개체를 정의하고 인증을 전달하는 것으로 시작합니다.
그런 다음 "새"객체를 정의합니다. API가 이를 수락하려면 이를 객체로 변환해야 합니다.
그런 다음 Sheets API를 호출하고
append
메서드를 사용합니다.이 엔드포인트의 경우 다음 네 가지 항목을 전달합니다.
그런 다음 오류 또는 결과 개체를 얻습니다. 우리의 경우 둘 다 console.log입니다.
결과적으로 이 쿼리의 영향을 받은 행을 나타내는 전체 개체를 얻습니다.
그게 다야. 이제 Google 시트에 데이터를 추가할 수 있습니다!
GitHub에서 이 버전을 찾을 수 있습니다.
읽어주셔서 감사합니다. 연결합시다!
제 블로그를 읽어주셔서 감사합니다. 내 이메일 뉴스레터를 구독하고 Facebook에 연결하거나
Reference
이 문제에 관하여(Node.js는 Google 시트에 데이터를 씁니다.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/dailydevtips1/node-js-write-data-in-a-google-sheet-74d텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)