How to optimise Apps Script code by using arrays to pull data from Google Sheets and format it?

前端 未结 2 1064
后悔当初
后悔当初 2020-12-21 23:02

I have a script that takes data from a gsheet and replaces placeholders on gdoc. I am looking to optimise the script by using arrays instead.

This is a sample of my

相关标签:
2条回答
  • 2020-12-21 23:26

    I believe you can optimize your code by using the appropriate method(s) to preserve the text format of your Google sheet values.

    Look into using the following method(s) of class Range from SpreadsheetApp service.

    Method getDisplayValue() returns the displayed value of the cell in the range. The value is a String. The displayed value takes into account date, time and currency formatting, including formats applied automatically by the spreadsheet's locale setting. Empty cells return an empty string.

    This should optimize your code by removing the necessity of regex. If I didn't understand your issue correctly, please leave a comment.


    References:

    • getDisplayValue()
    • getDisplayValues()
    • getRichTextValue()
    • getRichTextValues()
    0 讨论(0)
  • 2020-12-21 23:26

    You can try something like this. But it may not make any difference because creating files takes a long time.

    function optimise() {
      var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var vA= ss.getRange(1,1,ss.getLastRow(),4).getValues();
      var file = DriveApp.getFileById('FileID');
      for(var i=0;i<vA.length;i++){
        if(vA[i][0]){
          var Client=vA[i][1];
          var Amount=vA[i][2];
          var Date=vA[i][3];
          DriveApp.getFileById(file.makeCopy().getId()).setName(Client);  
          var body=DocumentApp.openById(documentId).getBody();
          body.replaceText('##Client##', Client).replaceText('##Amount##', Amount).replaceText('##Date##', Date)
        }
      }
    }
    

    I wonder if you need to saveAndClose() the document.

    0 讨论(0)
提交回复
热议问题