Google Sheet - Split Cell contents into rows and columns

后端 未结 2 2063
一向
一向 2021-02-11 11:31

Linked Google Sheet: https://docs.google.com/spreadsheets/d/1j2P2V0SCiE7QtK7kdCorpLfYQPFRghKMw4tuCYbqce0/edit?usp=sharing

I have a form that outputs all products and qua

相关标签:
2条回答
  • 2021-02-11 12:02

    You might be interested in a more general solution, rather than one that needs to rely on knowing the specific phrased in the input strings.

    This kvStringToArray() function will return an array that can be written directly to a spreadsheet use Range.setvalues(). It's pure JavaScript, so it can also be used outside of the Google Apps Script environment.

    A RegExp is used to successively identify key:value pairs in the input data, and the function assumes that there are "rows" of information that can be identified by repeats of already-discovered "keys".

    var formInput = "Product: NF900XC, Quantity: 3 Product: NF900, Quantity: 2 Product: N1930CB, Quantity: 2 Product: N2120, Quantity: 1 Product: NLPCR200, Quantity: 2 Product: N272, Quantity: 2";
    snippet.log(
      JSON.stringify(
        kvStringToArray(formInput)));
    
    /**
     * Convert a given string of key:value pairs into a two-dimensional
     * array, with keys as headers, and "items" as rows.
     * From: http://stackoverflow.com/a/34847199/1677912
     *
     * @param {string} str    A string containing key:value pairs.
     *
     * @returns {string[][]}  A two-dimensional array of strings.
     */
    function kvStringToArray( str ) {
      var re = /\s*(\w*?)\s*:\s*([^,\s]*)/g,  // See https://regex101.com/r/kM7gY1/1
          arr,           // array to capture key:value pairs
          data = [],     // array to return table
          row = [],      // array for building table rows
          headers = [];  // array of unique keys, for table header
      
      // Use a RegEx to identify individual key:value pairs
      while ((arr = re.exec(str)) !== null) {
        var key = arr[1];   // $1 matches key
        var value = arr[2]; // $2 matches value
        // Check if we should start a new row
        if (headers.indexOf(key) == 0) {
          data.push(row);
          row = [];
        }
        // Save this value in row
        row.push(value);
        // If this is the first time we've seen this key, add it to headers.
        if (headers.indexOf(key) == -1) headers.push(key);
      }
      data.push(row);  // save last row
      data.unshift(headers); // add headers
    
      return data;
    }
    <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

    0 讨论(0)
  • 2021-02-11 12:10

    Here is some code that I've tested and it works. The code removes all the words "Product: ", and replaces them with a comma. Then the code does something similar with the string "Quantity: ", replacing it with an empty string. Next it creates an array, and converts the array to a two dimensional array, so that the rows and columns can be written all in one action.

    function convertData() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sh = ss.getSheetByName('Form Submission');
    
      var data = sh.getRange("O2").getValue();
      //Logger.log(data);
      var firstProductRemoved = data.replace("Product: ", "");
      //Logger.log(firstProductRemoved);
    
      var allProductReplacedWithComma = firstProductRemoved.replace(/Product: /g,",");
      //Logger.log(allProductReplacedWithComma);
    
      var allQuantityReplacedWithNothing = allProductReplacedWithComma.replace(/Quantity: /g,"");
      //Logger.log(allQuantityReplacedWithNothing);
    
      var dataAsArray = allQuantityReplacedWithNothing.split(",");
    
      var outerArray = [], innerArray = [];
      var i=0;
    
      for (i=0;i<dataAsArray.length;i+=2) {
        innerArray = []; //reset every loop
    
        innerArray.push(dataAsArray[i]);
        innerArray.push(dataAsArray[i+1]);
        outerArray.push(innerArray);
      };
      //Logger.log(outerArray);
    
      var orderItemsSh = ss.getSheetByName('Order Items');
      orderItemsSh.getRange(orderItemsSh.getLastRow()+1, 15,outerArray.length, 2).setValues(outerArray);
    };
    
    0 讨论(0)
提交回复
热议问题