如何修改Google Apps脚本将生成的文档保存为docx格式?
实现Google Sheets数据自动生成docx格式文档的方法
你可以在现有Apps脚本基础上,通过Google Drive的文件导出功能,直接将填充好的Google Docs转换为docx格式,无需额外工具。具体修改步骤如下:
核心修改思路
- 保留原有「生成并填充Google Docs模板」的逻辑
- 新增将填充后的Google Docs导出为docx格式的步骤
- 将docx文件的链接写入表格(替代原Google Docs链接)
- 可选:删除临时生成的Google Docs文件,节省Drive存储空间
修改后的完整代码
function onOpen() { const ui = SpreadsheetApp.getUi(); const menu = ui.createMenu('生成养殖证明'); menu.addItem('生成养殖证明', 'createNewDocxFiles') menu.addToUi(); } function createNewDocxFiles() { // 替换为你的Google Docs模板ID const googleDocTemplate = DriveApp.getFileById('xxxxxxxx'); // 替换为存储docx文件的目标文件夹ID const destinationFolder = DriveApp.getFolderById('xxxxxxxxx'); const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data'); const rows = sheet.getDataRange().getValues(); rows.forEach(function(row, index){ // 跳过表头行 if (index === 0) return; // 跳过已生成过文件的行(第6列有内容则跳过) if (row[5]) return; // 复制模板并填充数据 const tempDocCopy = googleDocTemplate.makeCopy(`临时文档_${row[1]}, ${row[0]}`, destinationFolder); const doc = DocumentApp.openById(tempDocCopy.getId()); const body = doc.getBody(); const friendlyDate = new Date(row[3]).toLocaleDateString(); // 替换模板中的占位符 body.replaceText('{{First Name}}', row[0]); body.replaceText('{{Last Name}}', row[1]); body.replaceText('{{Position}}', row[2]); body.replaceText('{{Hire Date}}', friendlyDate); body.replaceText('{{Hourly Wage}}', row[4]); doc.saveAndClose(); // 将临时Google Docs导出为docx格式 const docBlob = tempDocCopy.getBlob().getAs('application/vnd.openxmlformats-officedocument.wordprocessingml.document'); const docxFile = destinationFolder.createFile(docBlob).setName(`${row[1]}, ${row[0]} 员工详情.docx`); // 将docx文件链接写入表格第6列 const docxUrl = docxFile.getUrl(); sheet.getRange(index + 1, 6).setValue(docxUrl); // 可选:删除临时的Google Docs文件 tempDocCopy.setTrashed(true); }) }
关键代码说明
getAs('application/vnd.openxmlformats-officedocument.wordprocessingml.document'):指定导出格式为docx的MIME类型createFile(docBlob):用导出的二进制数据创建docx文件setTrashed(true):将临时Google Docs移到回收站(彻底删除可改用DriveApp.getFileById(id).remove(),回收站可恢复更安全)
内容的提问来源于stack exchange,提问作者æHandal
相关产品推荐
相关产品推荐

