Skip to content

Instantly share code, notes, and snippets.

@ajaegers
Created March 1, 2017 21:19
Show Gist options
  • Save ajaegers/00c5e00374926a79a839800670a1fdf9 to your computer and use it in GitHub Desktop.
Save ajaegers/00c5e00374926a79a839800670a1fdf9 to your computer and use it in GitHub Desktop.
My usefull Google Sheets macros
/**
* A special function that runs when the spreadsheet is open, used to add a
* custom menu to the spreadsheet.
*/
function onOpen() {
var spreadsheet = SpreadsheetApp.getActive();
var menuItems = [
{name: "Unquote.li / Generate mysql insert on update from selection", functionName: "unquoteGenMySqlInsert_"}
];
spreadsheet.addMenu('MyHelpers', menuItems);
}
/**
* Creates a MySql INSERT ON DUPLICATE KEY UPDATE from Google Spreadsheets selected rows
* Formatted for a specific sheet
*/
function unquoteGenMySqlInsert_() {
// Init objects
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getSheetByName('Citations');
var ui = SpreadsheetApp.getUi();
// Vars
var aResults = [];
var aRow = [];
var sResult = "";
// Get Values from selected rows
var oRange = sheet.getActiveRange();
var aValues = oRange.getValues();
// Debugging output in ScriptEditor: View > Logs
Logger.log(oRange.getA1Notation());
Logger.log(aValues);
// Build MySql values
for(var r=0; r < aValues.length; r++){
aRow = aValues[r];
aResults.push('('+aRow[0]+', "'+aRow[3]+'")');
}
// Build Output
sResult = "# Update translations\n\
INSERT INTO `quotes` (`id`, `text_ru`)\n\
VALUES \n\
"+aResults.join(',\n ')+" \n\
ON DUPLICATE KEY UPDATE text_ru=VALUES(text_ru), updated_at=CURRENT_TIMESTAMP;";
// Show output in a modal with html content
ui.showModalDialog(HtmlService.createHtmlOutput('<textarea style="height:90vh; width:100%;">'+sResult+'</textarea>'), "Unquote / Requête MySql pour mise à jour des traductions");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment