Wednesday, May 22, 2013

Scripting struggles and a working Script!

I have been struggling with my script as I have been looking for too broad a use. I have a specific use in mind and have been trying to make it useful for all occurances. Once I made this mental switch, the problem was not as difficult and the major change I made from previous failed attempts was to name the range in my sheet to make it easier for my script to find.

As you can see, I tried to steal from previous scripts and the Google Developers tutorials are awesome. So here is my updated code that works to read a spreadsheet cell that contains website URL that contains my LaTeX problem and writes it to the body of the Google Doc.

It works for a given row (highlighted by the var currentStudentObject = studentObjects[0] command).
Next, I will run this through a loop to do it for each student and the Document Key will be part of the Spreadsheet Column Data as well. I will also make the Date get pulled from the spreadsheet and will make it look better in the document.

(As a side note, by putting // in the code, everything after it on that line is considered text and not code, so I put reminders and notes in there for myself).

function writeToDoc() {
  //Try to use a named range to pull the problemURL out of each row data. from:
var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];

  // Get the range of cells that store student data.
  var studentInformationRange = ss.getRangeByName('StudentData');

  // For every row of student data, generate a student object.
  var studentObjects = getRowsData(sheet, studentInformationRange);
  var currentStudentObject = studentObjects[0]  //get the 0th row of data from the studentObjects array, to do: run a loop to do this for every student
  //This fetches a document by ID (found in the URL) and opens it up.

  var doc = DocumentApp.openById('1Haex8jdw1n1G1dwKw9Y9i1iMbW3b74D9_o3EfrDvnp0'); //would like to replace this with the file key by student
  //You could also use var doc = DocumentApp.create(name) to create a new document instead of opening an existing one.

  // The following code fetches the picture from the problemUrl
  // and puts it in the document created above taken ideas from:

  //find the Url
  var problemUrl = currentStudentObject.problemUrl; //replace from student problem from column named Problem URL in the student Data row.
var problemBlob = UrlFetchApp
  //find the body of the document
  var body = doc.getActiveSection();
  //put the image into the body of the document found above. Got information from here:

  var dateForClass = body.appendParagraph('Seat Problem for Class Date of ##-##-##');
  var seatProblem = body.appendImage(problemBlob);