我想在 Google 表格中提取多个带分隔符的数据,并通过标签将其添加到文档中

I want to extract multiple data with delimiters in Google Sheets and add it to Docs through tags

我想通过标签解决有关 Google 表格和可填写文档的问题。事实是,我已经按照此 site resulting in a nice Doc in can share with the client, but what if one client wants multiple cars quotations? My cells in Sheets will be populated with multiple comma separated strings like this image 中的说明为一位客户的一个请求(例如,一位客户想要一份汽车报价)做了正确的处理。这就是为什么我想执行以下步骤:

所以,我希望有人有时间帮助我解决这个问题,因为我是编程新手,也是 Google Apps 脚本方面的新手。非常感谢!

PS:你可以看我要找的结果,以防一个客户在一个报价中想要多个模型here. Also, you can search for the Doc template of my quotation model here and the Sheets example here

//-------------------------------------------------------------------------------------------------------------
//Function to add one client's data to a Doc template from Sheets`
//-------------------------------------------------------------------------------------------------------------
function CreateNewGoogleDocs() {

  const googleDocTemplate = DriveApp.getFileById('Doc's ID');
  const destinationfolder = DriveApp.getFolderById('Folder's ID');
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet's Name');
  const rows = sheet.getDataRange().getValues();

  rows.forEach(function(row,index) {
    if(index === 0) return;
    if(row[10]) return;
 
//Name the file and get its elements
const copy = googleDocTemplate.makeCopy(`Quotation ${row[0]}`, destinationfolder);
const doc = DocumentApp.openById(copy.getId())
const body = doc.getBody();
const header = doc.getHeader();

//Data conversion  
const friendlyDate = new Date(row[9]).toLocaleDateString("en-GB");

//Currency conversion 
var n1 = new Number(row[6]); //Price
var n2 = new Number(row[6]*0.16); //Tax
var n3 = new Number(n1+n2+350); //Final price

var formatted = {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
};

console.log(formatted);

const friendlyCurrency1 = n1.toLocaleString("en-US", formatted)
const friendlyCurrency2 = n2.toLocaleString("en-US", formatted)
const friendlyCurrency3 = n3.toLocaleString("en-US", formatted)


//Replace data in header   
header.replaceText('{{Quotation}}', row[0]);
   
//Replace general data in the body
body.replaceText('{{Client}}',row[1]);
body.replaceText('{{Brand}}',row[2]);
body.replaceText('{{Model}}',row[3]);
body.replaceText('{{Year}}',row[4]);
body.replaceText('{{Date}}',friendlyDate);

//Replace financial data
body.replaceText('{{Price}}',friendlyCurrency1);
body.replaceText('{{Tax}}',friendlyCurrency2);
body.replaceText('{{Final price}}',friendlyCurrency3);

//Save and create Doc's URL
doc.saveAndClose();
const url = doc.getUrl();
sheet.getRange(index+1,11).setValue(url)

   })  
  }

我修改了您上面提供的代码。见下文。

代码:

// Initialize as global variable for easier access
const googleDocTemplateMain = DriveApp.getFileById('');
const googleDocTemplateTable = DriveApp.getFileById('');
const destinationfolder = DriveApp.getFolderById('');
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data');

//-------------------------------------------------------------------------------------------------------------
//Function to add one client's data to a Doc template from Sheets`
//-------------------------------------------------------------------------------------------------------------

function CreateNewGoogleDocs() {
  // Used getDisplayValues for easier parsing
  const rows = sheet.getDataRange().getDisplayValues();

  rows.forEach(function (row, index) {
    if (index === 0) return;

    var quotations;
    // If multiple quotations in a row
    if (row[0].includes(",")) {
      quotations = row[0].split(",");
      // Here we check if a document has already been generated by looking at 'Document Link'
      // and has the same number of elements compared to the first column.
      if (row[10] && row[10].split(",").length == quotations.length) return;

      // Remove the values of tax and finalPrice then recalculate
      sheet.getRange(index + 1, 8, 1, 2).clearContent();
      // Split all columns, and access them with index2 inside the forEach loop
      for(var i=0; i<10; i++) {
        if (i == 6) {
          row[i] = row[i].substring(1);
          row[i] = row[i].split(",$");
        }
        else 
          row[i] = row[i].split(",");
      }

      // Process each element in the row
      quotations.forEach(function(quotation, index2) {
        var elements = [row[0][index2], row[1][index2], 
                        row[2][index2], row[3][index2],
                        row[4][index2], row[5][index2],
                        row[6][index2], row[7][index2], 
                        row[8][index2], row[9][index2]];
        processSingleQuotation(elements, index);
      });
    }
    else {
      if (row[10]) return;
      // Remove the values of tax and finalPrice then recalculate
      sheet.getRange(index + 1, 8, 1, 2).clearContent();
      processSingleQuotation(row, index);
    }
  });
}

function processSingleQuotation(row, index){
  var copyMain, docMain, copyTable, docTable, bodyTable;
  var filename = `Quotation ${row[0].trim()}`;
  var files = destinationfolder.getFilesByName(filename);

  // If true, then filename already exists
  // Use existing file instead
  if (files.hasNext())
    docMain = DocumentApp.openById(files.next().getId());
  else {
    copyMain = googleDocTemplateMain.makeCopy(`Quotation ${row[0].trim()}`, destinationfolder);
    docMain = DocumentApp.openById(copyMain.getId());
  }
  // Template data for main document
  const bodyMain = docMain.getBody();
  const headerMain = docMain.getHeader();

  // Template data for table
  copyTable = googleDocTemplateTable.makeCopy(`Table ${row[0].trim()}`, destinationfolder);
  docTable = DocumentApp.openById(copyTable.getId());
  bodyTable = docTable.getBody();

  const friendlyDate = new Date(convertDate(row[9].trim())).toLocaleDateString("en-GB");

  var price = formatPrice(row[6].trim());
  
  //Currency conversion 
  var n1 = new Number(price); //Price
  var n2 = new Number(price * 0.16); //Tax
  var n3 = new Number(n1 + n2 + 350); //Final price

  var formatted = {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  };

  const friendlyCurrency1 = n1.toLocaleString("en-US", formatted)
  const friendlyCurrency2 = n2.toLocaleString("en-US", formatted)
  const friendlyCurrency3 = n3.toLocaleString("en-US", formatted)

  // Replace data in main file   
  headerMain.replaceText('{{Quotation}}', row[0].trim());
  // Replace general data in the body
  bodyMain.replaceText('{{Client}}', row[1].trim());
  bodyMain.replaceText('{{Date}}', friendlyDate);

  // Replace table template values
  bodyTable.replaceText('{{Brand}}', row[2].trim());
  bodyTable.replaceText('{{Model}}', row[3].trim());
  bodyTable.replaceText('{{Year}}', row[4].trim());
  // I didn't include colors as im not sure what available colors are available
  // I didn't include availability as im not sure how to determine the availability

  // Replace financial data
  bodyTable.replaceText('{{Price}}', friendlyCurrency1);
  bodyTable.replaceText('{{Tax}}', friendlyCurrency2);
  bodyTable.replaceText('{{Final price}}', friendlyCurrency3);

  for(var i=0; i<bodyTable.getNumChildren();i++){ //run through the elements of the template doc's Body.
    switch (bodyTable.getChild(i).getType()) { //Deal with the various types of Elements we will encounter and append.
      case DocumentApp.ElementType.PARAGRAPH:
        bodyMain.appendParagraph(bodyTable.getChild(i).copy());
        break;
      case DocumentApp.ElementType.LIST_ITEM:
        bodyMain.appendListItem(bodyTable.getChild(i).copy());
        break;
      case DocumentApp.ElementType.TABLE:
        bodyMain.appendTable(bodyTable.getChild(i).copy());
        break;
    }
  }

  // Delete after copying contents to main file
  docTable.saveAndClose();
  Drive.Files.remove(copyTable.getId());

  //Save and create Doc's URL
  docMain.saveAndClose();
  const url = docMain.getUrl();
  sheet.getRange(index + 1, 11).setValue(url);

  // Write tax and finalPrice
  var [[tax, finalPrice]] = sheet.getRange(index + 1, 8, 1, 2).getDisplayValues();

  if (tax != '') {
    tax += ',';
    finalPrice += ',';
    sheet.getRange(index + 1, 8).setValue(tax + friendlyCurrency2);
    sheet.getRange(index + 1, 9).setValue(finalPrice + friendlyCurrency3);
  }
  else {
    sheet.getRange(index + 1, 8).setValue(friendlyCurrency2);
    sheet.getRange(index + 1, 9).setValue(friendlyCurrency3);
  }
}

function convertDate(date) {
  var dateArray = date.split("/");
  return dateArray[1] + '/' + dateArray[0] + '/' + dateArray[2];
}

function formatPrice(price) {
  return Number(price.replace(/[$,]+/g,""));
}

Sheet数据:

文件夹:

生成的示例文件:

主模板:

Table 模板:

注意!!:

  • 这会重新计算您的税费和最终价格
  • 我将模板分成两部分,主体和每个引用的数据,这样我们就可以循环进入 table 模板并在每次完成时附加到主模板。
  • 由于不确定我如何确定每个报价的价值,可用性和颜色被排除在外。根据需要添加即可。
  • 查看评论了解更多信息。