首页 > 解决方案 > 使用 Google Docs 在我的 GAS 发票生成器中的数组开头未定义

问题描述

我的脚本从 Google 电子表格中获取家具价格和详细信息,并将其带入 Google 文档插件中,这会显示一个侧边栏,您可以在其中选择家具范围,并在您点击后将价格输入到带有数量输入字段的侧边栏中在侧边栏上生成发票,然后用单位代码、名称、价格和数量填充 Google 文档表。

除了 unitCode 的第一次迭代 unitName unitPrice 等在它说 unitCode、unitPrice、unitName 等之前未定义之外,一切正常。对不起,代码混乱,这是一项正在进行中的工作,尚未整理或示例代码真正被删除.

此外,我觉得可能有一种更简单的方法来实现我想要做的事情,可能只是使用 G 表本身,所以绝对愿意接受建议。

提前致谢。未定义显示的照片

这是发送到 GS 文件的 HTML

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
    <!-- The CSS package above applies Google styling to buttons and other elements. -->

    <style>
    .units {
    margin-top:20px;
    width:100%;
 }
    </style>
  </head>
  <body>
    <div class="sidebar branding-below">
    <label>Client Name</label>
    <input type="text" name="client_name" id="client_name"><br>
    <label>Client Phone</label>
    <input type="text" name="client_phone" id="client_phone"><br>
    <label>Client Email</label>
    <input type="text" name="client_email" id="client_email"><br>
 <!-- Multiple Radios -->
<div class="form-group">
  <label class="col-md-4 control-label" for="furntype">Furniture Type</label>
  <div class="col-md-4">
  <div class="radio">
    <label for="furntype-0">
      <input type="radio" name="furntype" id="furntype-0" value="0" checked="checked">
      6S
    </label>
    </div>
  <div class="radio">
    <label for="furntype-1">
      <input type="radio" name="furntype" id="furntype-1" value="1">
      6S Compact
    </label>
    </div>
  </div>
</div>
<span id="theFurnType"></span>



    
      <form>
</form>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>

      /**
       * On document load, assign click handlers to each button and try to load the
       * user's origin and destination language preferences if previously set.
       */
      $(function() {


  
        $('input:radio').click(function() {
        
        var sheetDataz = google.script.run
    .withFailureHandler(function(err){
        console.error("error occured", err);
    })
    .withSuccessHandler(function(res){
    var tab = '<div class="units"><div >';
    var price = res[2];
    var theUnitCode = res[0];

    $.each(res[1], function(index, value){
    var aPrice = price[index];
   var thePrice = parseFloat(aPrice).toFixed(2);
   var unitCode = theUnitCode[index];
   tab += '<span>'+value+'</span><input type="text" class="unit"  unitcode="'+unitCode+'" unitname="'+value+'" id="'+index+'" price="'+thePrice+'" value="0" style="float:right; width:40px;"><hr>';
    });
    tab += '<br><button type="button" id="doInvoice">Create Invoice</button></div>';
    $('#theFurnType').html(tab);
            $('#doInvoice').click(replaceIt);
    }).getSheetData($(this).val());
  });
  
  
          function replaceIt() {
      var client_name = $('#client_name').val();
      var client_phone = $('#client_phone').val();
      var client_email = $('#client_email').val();
      var acr = client_name.match(/\b(\w)/g); 
        var invoice_num = acr.join('');
        var date = GetTodayDate();
        var invoice_num = invoice_num+'_'+date;
        var theUnits = {};
        $('.unit').each(function() {
         theUnits.unitQuantity += $(this).val()+',';
         theUnits.unitPrice += $(this).attr("price")+',';
         theUnits.unitName += $(this).attr("unitname")+',';
         theUnits.unitCode += $(this).attr("unitcode")+',';
        });
              google.script.run.doReplace(client_name,client_phone,client_email,invoice_num,date,theUnits);
      }

  
  
      });
 
 
 

function GetTodayDate() {
   var tdate = new Date();
   var dd = tdate.getDate(); //yields day
   var MM = tdate.getMonth(); //yields month
   var yyyy = tdate.getFullYear(); //yields year
   var currentDate= dd + "-" +( MM+1) + "-" + yyyy;

   return currentDate;
}





    </script>
  </body>
</html>

这是GS文件

/**
 * @NotOnlyCurrentDoc
 *
 * The above comment directs Apps Script to limit the scope of file
 * access for this add-on. It specifies that this add-on will only
 * attempt to read or modify the files in which the add-on is used,
 * and not all of the user's files. The authorization request message
 * presented to users will reflect this limited scope.
 */

/**
 * Creates a menu entry in the Google Docs UI when the document is opened.
 * This method is only used by the regular add-on, and is never called by
 * the mobile add-on version.
 *
 * @param {object} e The event parameter for a simple onOpen trigger. To
 *     determine which authorization mode (ScriptApp.AuthMode) the trigger is
 *     running in, inspect e.authMode.
 */
function onOpen(e) {
  DocumentApp.getUi().createAddonMenu()
      .addItem('Start', 'showSidebar')
      .addToUi();
}

/**
 * Runs when the add-on is installed.
 * This method is only used by the regular add-on, and is never called by
 * the mobile add-on version.
 *
 * @param {object} e The event parameter for a simple onInstall trigger. To
 *     determine which authorization mode (ScriptApp.AuthMode) the trigger is
 *     running in, inspect e.authMode. (In practice, onInstall triggers always
 *     run in AuthMode.FULL, but onOpen triggers may be AuthMode.LIMITED or
 *     AuthMode.NONE.)
 */
function onInstall(e) {
  onOpen(e);
}

/**
 * Opens a sidebar in the document containing the add-on's user interface.
 * This method is only used by the regular add-on, and is never called by
 * the mobile add-on version.
 */
function showSidebar() {
  var ui = HtmlService.createHtmlOutputFromFile('sidebar')
      .setTitle('Infinity Invoice Generator');
  DocumentApp.getUi().showSidebar(ui);
}

/**
 * Gets the text the user has selected. If there is no selection,
 * this function displays an error message.
 *
 * @return {Array.<string>} The selected text.
 */

function getSheetData(furnType) {
var ss = SpreadsheetApp.openById('1jLpJ35Szy6R3DDVVuOmi0Cw462ukI2DWzHG6VxYWd1g');
  var sheets = ss.getSheets();
  if(furnType == 0) {
    var ranges = [sheets[0].getRange('A2:A11').getValues(), sheets[0].getRange('B2:B11').getValues(), sheets[0].getRange('H2:H11').getValues()];
  }
  if(furnType == 1) {
      var ranges = [sheets[1].getRange('A2:A10').getValues(), sheets[1].getRange('B2:B10').getValues(), sheets[1].getRange('H2:H10').getValues()];
  }
  return ranges;
}

      function doReplace(client_name,client_phone,client_email,invoice_num,date,theUnits) { 
      var body = DocumentApp.getActiveDocument().getBody();
        

        
        var tables = body.getTables();
        var table = tables[2];
        

var unitQuantity = theUnits.unitQuantity.split(',');
var unitCode = theUnits.unitCode.split(',');
var unitName = theUnits.unitName.split(',');
var unitPrice = theUnits.unitPrice.split(',');
        
        var style1 = {};
style1[DocumentApp.Attribute.FONT_FAMILY] = 'Arial';
style1[DocumentApp.Attribute.FONT_SIZE] = 12;
style1[DocumentApp.Attribute.BOLD] = true;
  style1[DocumentApp.Attribute.BACKGROUND_COLOR] = '#D9D9D9';
  style1[DocumentApp.Attribute.FOREGROUND_COLOR] = '#000000';
        
 

        var style2 = {};
style2[DocumentApp.Attribute.FONT_FAMILY] = 'Arial';
style2[DocumentApp.Attribute.FONT_SIZE] = 12;
style2[DocumentApp.Attribute.BOLD] = false;
style2[DocumentApp.Attribute.BACKGROUND_COLOR] = '#F3F3F3';
style2[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = 'CENTER';
style2[DocumentApp.Attribute.FOREGROUND_COLOR] = '#000000';
        
        
   var i;
for (i = 0; i < unitQuantity.length; i++) {
      var tr = table.appendTableRow();
        var td = tr.appendTableCell(''+unitCode[i]+'').setAttributes(style1);
        var td = tr.appendTableCell(''+unitName[i]+'').setAttributes(style2);
        var td = tr.appendTableCell(''+unitPrice[i]+'').setAttributes(style2);
        var td = tr.appendTableCell(''+unitQuantity[i]+'').setAttributes(style2);
}

       
        
        
       body.replaceText("{{ClientName}}", client_name);
        body.replaceText("{{ClientPhone}}", client_phone);
         body.replaceText("{{ClientEmail}}", client_email);
         body.replaceText("{{InvoiceNumber}}", invoice_num);
         body.replaceText("{{CurrentDate}}", date);
      }

标签: javascriptjquerygoogle-apps-script

解决方案


问题在于replaceIt功能,特别是您构建theUnits对象的方式。用空字符串初始化对象中的每个属性,这将解决问题:

function replaceIt() {
  var client_name = $('#client_name').val();
  var client_phone = $('#client_phone').val();
  var client_email = $('#client_email').val();
  var acr = client_name.match(/\b(\w)/g);
  var invoice_num = acr.join('');
  var date = GetTodayDate();
  var invoice_num = invoice_num + '_' + date;
  var theUnits = {
    unitQuantity: "",
    unitPrice: "",
    unitName: "",
    unitCode: ""
  };
  $('.unit').each(function() {
    theUnits.unitQuantity += $(this).val() + ',';
    theUnits.unitPrice += $(this).attr("price") + ',';
    theUnits.unitName += $(this).attr("unitname") + ',';
    theUnits.unitCode += $(this).attr("unitcode") + ',';
  });
  google.script.run.doReplace(client_name, client_phone, client_email, invoice_num, date, theUnits);
}


推荐阅读