Search code examples
google-apps-scriptgoogle-sheetsgraph

google sheet, copying sparkline's data


is there a way where I can just copy the Sparkline graph so that if I deleted the Sparkline's value I can still have the Sparkline's graph on another cell using a simple script that can be time driven

this is my Sparkline's graph I want to delete the Sparkline's value but retain its graph


Solution

  • Note:

    Always share a sample sheet/screenshot/piece of code of what you're working on when possible so that that we will be able to visualize better your goal and this will also help the community to provide you with a better answer/recommendation.

    Recommendation

    On my testing, I have found out that there's no simple way to just copy the Sparkline graph without it's data. With that being said, you may refer to this alternative method below.

    Here's a sample sheet, where I've created a data with a sparkline graph. On the right (Columns D and E), I've created a space where the copied sparkline data and graph will be placed into:

    enter image description here

    Here's the Apps Script code:

    function copy(){
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getActiveSheet();
      var d = new Date();
      var timeStamp = d.toLocaleDateString()+" at "+d.toLocaleTimeString();
      var data = sheet.getRange('Sheet1!B4:B').getValues(); //Get sparkline data from the sample sheet on Column B (from row 4 and below).
      var array = []; //the array that will be the container of the original Sparline data
      for(var x=0; x<data.length;x++){ //This loop removes all null/empty values from variable 'data' and only keep the ones that aren't and then will be put into the variable 'array'
        if(data[x] != ''){
          array[x] = data[x].toString();
          sheet.getRange(3+x,4).setValue(array[x]); //Puts the copied data from 'array' to the Column D on row 3 and below (or 'D3:D') 
        }
      }
      sheet.getRange('E2').setValue("=SPARKLINE(D3:D)").setBackground('lime'); //Adds a new Spakline graph on cell 'E2' that uses the copied data from 'D3:D'
      sheet.getRange('E3').setValue("Copied on "+timeStamp); //(Optional) Add timestamp of the copied data for reference
      ss.toast('Copying sparkline data done at '+timeStamp); //(Optional) Add toast message on the sheet
    }
    

    After running the code, this will be the result on the sample sheet:

    enter image description here

    If the original sparkline data changes, the copied data will still be accessible on your sheet (except if the code runs again, as this will override the previous copied data with the new one).

    enter image description here