Saturday, September 29, 2012

Latex Tables from Google Spreadsheets

Basically, I'm writing my thesis now, and so I needed to make a lot of latex tables. I have R->latex and matlab->latex scripts lying about, but as I've lost the inclination to redo experiments, I find it easier to just use the existing latex tables in my documents. However, reformatting them is kind of a pain.

So I would generally use Excel for this, but I find Google spreadsheets to be easier to use because I'm using more than 2 computers more often these days. I hate having to copy things back and forth and as friendly as google-drive is, Excel is less so. My workstation in the lab, for example is the French language version, which I can barely use (the commas kill me.)

Anyways so here it is, Google docs spreadsheets have a Javascript runtime that is exposed much like VBA. You can use it to write custom functions and other things. I wrote a handy button that will take my selected range and output a latex table.

Once you have your sheet filled out, you can then hit Tools->Script Manager from the menu bar. Hit "spreadsheet."

In another browser window, the javascript editor will show up with a handy example provide by Google. Here's what I did with mine.

 function latexify() {  
  var range = SpreadsheetApp.getActiveRange();  
  var numRows = range.getNumRows();  
  var numCols = range.getNumColumns();  
  var values = range.getValues();  
  var cs = new Array(numCols);  
  var strRows = "";   
    
  for(var k = 0; k < numCols; k++){  
   cs[k] = 'c';  
  }  
  strRows = "\\begin{table}\n";  
  strRows += "\\centering\n";  
  strRows += "\\begin{tabular}";  
  strRows += "{|" + cs.join("|") + "|}\n"  
  strRows += "\\hline\n";  
    
  for (var i = 0; i <= numRows - 1; i++) {  
   var row = values[i];  
   for (var j = 0; j <= numCols - 1; j++){  
    var cell = row[j];  
    strRows = strRows + cell;  
    if(j < numCols-1)  
     strRows = strRows + " & ";  
   }  
   strRows += "\\\\ \n\\hline\n";  
   }  
  strRows += "\\hline";  
  strRows += "\\end{tabular}\n";  
  strRows += "\\label{table:table}\n";  
  strRows += "\\caption{\\small{}} \n";  
  strRows += "\\end{table}\n";  
   
  Logger.log(strRows);  
 };  

Lovely, isn't it? Choose Run from the menu in the editor, and then View->Logs to show the output. Documentation is available from the Help menu, but I found the API Reference most useful.