如何通过Sheets和Docs API在Node.js后端将Google Sheets选区复制到Google Docs
谷歌Sheet选区内容同步到Docs(Node.js实现方案)
本方案完全基于谷歌公开的REST API实现,无需依赖App Script,符合自研Node.js后端的技术选型要求。
前置依赖
- 需在谷歌云控制台启用
Google Sheets API v4和Google Docs API v1 - Node.js端推荐使用谷歌官方维护的
googleapisSDK调用接口,无需手动封装HTTP请求
整体实现步骤
- 第一步:调用Google Sheets API的
spreadsheets.values.get接口,拉取指定选区的表格内容。如果需要保留单元格格式、合并单元格等属性,可额外调用spreadsheets.get接口,指定fields参数拉取对应范围的userEnteredFormat、mergeCells等元数据。 - 第二步:调用Google Docs API的
documents.batchUpdate接口,先向目标位置插入对应行列数的空表格,再逐单元格填充内容,如果有格式需求可追加格式更新的请求完成样式对齐。
核心代码示例
1. 初始化API客户端
const { google } = require('googleapis'); // 认证支持服务账号或者OAuth2两种方式,根据自身业务场景选择 const auth = new google.auth.GoogleAuth({ keyFile: '你的服务账号密钥文件路径.json', scopes: [ 'https://www.googleapis.com/auth/spreadsheets.readonly', 'https://www.googleapis.com/auth/documents' ] }); const sheetsClient = google.sheets({ version: 'v4', auth }); const docsClient = google.docs({ version: 'v1', auth });
2. 读取Sheet指定选区内容
async function getSheetSelection(spreadsheetId, range) { // 示例range格式:'Sheet1!A1:D5' const response = await sheetsClient.spreadsheets.values.get({ spreadsheetId, range }); return response.data.values; }
3. 向Docs插入表格
async function insertSheetDataToDoc(documentId, sheetData, insertPosition = 1) { const rowNum = sheetData.length; const columnNum = sheetData[0].length; const requests = []; // 先插入对应尺寸的空表格 requests.push({ insertTable: { location: { index: insertPosition }, rows: rowNum, columns: columnNum } }); // 逐单元格填充内容 sheetData.forEach((row, rowIndex) => { row.forEach((cellContent, colIndex) => { // 注意:Docs的内容索引需要计算表格结构标记的占位,下方计算方式适配常规无嵌套内容的文档 const cellInsertIndex = insertPosition + 2 + rowIndex * (columnNum + 1) + colIndex; requests.push({ insertText: { location: { index: cellInsertIndex }, text: String(cellContent || '') } }); }); }); await docsClient.documents.batchUpdate({ documentId, requestBody: { requests } }); }
注意事项
- 表格插入位置的索引计算规则:Google Docs的内容索引从1开始计数,表格的每个单元格前都有不可见的结构标记,计算单元格内容插入位置时需要把这些标记的占位算入,避免内容插入错位。
- 如果需要完全复刻Sheet的样式,比如单元格背景色、字体样式、边框、合并单元格等,可以在拉取Sheet数据时额外请求对应格式字段,插入表格后追加
updateTableCellStyle、updateTextStyle、mergeTableCells等请求即可实现样式对齐。
内容的提问来源于stack exchange,提问作者Rasmus Puls
相关产品推荐
相关产品推荐

