要在Node.js中使用Google API密钥访问Google Drive和Google Sheets,您需要遵循以下步骤:
const { google } = require('googleapis');
// 设置API密钥
const apiKey = 'YOUR_API_KEY';
// 初始化Google Drive服务
const drive = google.drive({ version: 'v3', auth: apiKey });
// 初始化Google Sheets服务
const sheets = google.sheets({ version: 'v3', auth: apiKey });
// 示例:列出Google Drive中的文件
async function listDriveFiles() {
try {
const res = await drive.files.list({
pageSize: 10,
fields: 'nextPageToken, files(id, name)',
});
const files = res.data.files;
if (files && files.length) {
files.map((file) => {
console.log(`${file.name} (${file.id})`);
});
} else {
console.log('No files found.');
}
} catch (err) {
console.error('The API returned an error:', err.response.data);
}
}
// 示例:读取Google Sheets中的数据
async function readSheetData(spreadsheetId, range) {
try {
const res = await sheets.spreadsheets.values.get({
spreadsheetId,
range,
});
const rows = res.data.values;
if (rows) {
rows.map((row) => {
console.log(row);
});
} else {
console.log('No data found.');
}
} catch (err) {
console.error('The API returned an error:', err.response.data);
}
}
// 调用函数
listDriveFiles();
readSheetData('YOUR_SPREADSHEET_ID', 'Sheet1!A1:D10');
请确保将 'YOUR_API_KEY'
替换为您的实际API密钥,以及将 'YOUR_SPREADSIDE_ID'
替换为您要访问的Google Sheets文档的ID。
领取专属 10元无门槛券
手把手带您无忧上云