首页 > 解决方案 > 自动将数据从 Google 表格复制到 Google 文档模板

问题描述

每次有人提交 Google 表单时,我都需要自动填充 Google 文档模板。我有包含所有信息的 Google 表格,并且我已经设置了模板文档,其中包含我想要填充的区域,但我找不到任何地方可以显示如何做我需要做的事情。

请问有人可以分享知识吗?

标签: google-apps-scriptgoogle-sheetsgoogle-docs

解决方案


您正在寻找的是'Auto Fill Google Doc From Form'。您需要使用 onFormSubmit 触发器向工作表添加一个函数。在该功能中,您将

  • 参考您的模板
  • 从该模板创建一个新文档
  • 生成参考号
  • 使用信息更新新文档

它看起来像这样:

function autoFillGoogleDocFromForm(e) {
     // Get your values from form
     let timestamp = e.values[0];
     let value1 = e.values[1];
     let value2 = e.values[2];
     // ... continue for however many values you are returning

     // Get your template file
     let templateFile = DriveApp.getFileById('your_file_id_here');

     // Set the folder you want to create the new file in
     let responseFolder = DriveApp.getFolderById('your_folder_id_for_new_doc'); 

     // Create your reference number
     let refNumber = createReferenceNumber();  // You'll need to write this

     // Create your new file
     let newDocName = createNewDocFileName();  // You'll need to write this
     let copy = file.makeCopy(newDocName , responseFolder); 
     
     // Open the newly created document so it can be updated
     let doc = DocumentApp.openById(copy.getId()); 

     // Update the doc with your new data
     let body = doc.getBody();

     // The template should have placeholders {{ }} to replace the value with
     body.replaceText('{{value1}}', value1); 
     body.replaceText('{{value2}}', value2);  
     body.replaceText('{{Reference Number}}', refNumber); 

     doc.saveAndClose();  
}

当然,您需要编写一个脚本来创建参考号,以及一个用于生成文件名的脚本。(或者只是将它们在线添加,它们不必是单独的脚本。)您的问题提到您无法生成参考号。我建议创建一个新问题,其中包含您尝试过的代码以及您收到的任何错误。


推荐阅读