简体   繁体   中英

Ingest data from Google sheets to make a gantt chart on Google script and serve the HTML as web app

I'm attempting to create a Google Gantt Chart on Google Script, pulling data from a Google Sheets spreadsheet to serve the HTML as web app. I managed to do the trick with other types of charts, but I think there's some problem with the date format, as I keep getting erros like "Invalid data table format: column #3 must be of type 'date'"

I'm not familiar with Javascript, so I'm really lost here. Here is the code on my Code.gs. The file has to be private, it's on my work Gsuite, but is a simple test with data formatted as in the Google Gantt Charts documentation .

function doGet() {

  return HtmlService
  .createTemplateFromFile("Index")
  .evaluate()
  .setTitle("MKT Simple Cycle")
  .setSandboxMode(HtmlService.SandboxMode.IFRAME);  
}


function getCycle() {

  var ssID   = "1p4jEZtSk4GoVWvR9OrZj2ou1dpUbl6GHYUlJ1bSVY-s",
  sheet  = SpreadsheetApp.openById(ssID).getSheets()[0],
  data   = sheet.getDataRange().getValues();
  return data

}

And here is the code on my Javascript.html:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
google.charts.load('current', {'packages':['gantt']});
google.charts.setOnLoadCallback(getCycle);

function getCycle() {
  google.script.run.withSuccessHandler(drawChart).getCycle();
}

function drawChart(rows) {

  var data = google.visualization.arrayToDataTable(rows, false);

  var options = {
    height: 400,
    gantt: {
      trackHeight: 30
    }
  };

  var chart = new google.visualization.Gantt(document.getElementById('Cycle'));

  chart.draw(data, options);

}

The problem here is that sheet.getDataRange().getValues(); returns strings, and the Gantt chart needs Start Date and End Date to be javascript Date objects.

Cycle through the array you have in data , converting the strings in cells 3 and 4 (if you have a Resource ID column in your sheet, or cells 2 and 3 if you don't) with Date objects.

row[2] = new Date(row[2]);
row[3] = new Date(row[3]);

That should fix the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM