Skip to content

Instantly share code, notes, and snippets.

@jacksonpradolima
Created July 5, 2017 18:49
Show Gist options
  • Save jacksonpradolima/afb55d7bf86d1e5902e2442a5ac19478 to your computer and use it in GitHub Desktop.
Save jacksonpradolima/afb55d7bf86d1e5902e2442a5ac19478 to your computer and use it in GitHub Desktop.
Google Sheets script to allow export cells to LaTeX tables (adapted from http://alienexp.blogspot.com.br/2012/09/latex-tables-from-google-spreadsheets.html)
<div style="font-family: sans-serif;">
<? var data = generateLaTeXTable(); ?>
<textarea rows="20" cols="40" style="overflow:scroll;"><?= data ?></textarea>
<br>
<input type="button" value="Close" onclick="google.script.host.close()" />
</div>
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu('Scripts')
.addItem('Convert to LaTeX table', 'showLaTeXTableDialog')
.addToUi();
}
function showLaTeXTableDialog() {
var html = HtmlService.createTemplateFromFile('latex_table').evaluate();
SpreadsheetApp.getUi().showSidebar(html);
}
function generateLaTeXTable(){
try{
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";
return strRows;
}catch(e){
return null
}
}
@jacksonpradolima
Copy link
Author

For general guidance on setting up a script in Google Sheets, see this quickstart guide.

To use this script:

  1. Go to option menu Tools > Script editor...
  2. In the script editor, go to option menu File > New > Script file
  3. Name the file latexfy.gs and paste in the contents of latexfy.gs. Save the file, File > Save.
  4. In the script editor, go to option menu File > New > Html file
  5. Name the file latex_table.html and paste in the contents of dialog.html. Save the file, File > Save.
  6. Back in your spreadsheet, you should now have a new menu called Scripts. Refresh the page if necessary.
  7. Select the cells you want to export to LaTeX table.
  8. Go to option menu Scripts > Convert to LaTeX table and the sidebar should open, showing the LaTeX code generated.

You can leave the script sidebar open. When you export new cells the script sidebar will be updated.

Many thanks to Dave Rim for creating the original script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment