Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Google Apps script to generate Android strings.xml files from Google Sheets
// Add menu
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Android')
.addItem('Export', 'exportTranslations')
.addToUi();
}
function exportTranslations() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getActiveSheet();
const rowsData = getDataRange(sheet);
const folder = DriveApp.createFolder("Translations");
const strings = [];
for (let i = 0; i < rowsData.length; i++) {
const row = rowsData[i];
const stringFile = constructTranslation(row);
strings.push(stringFile.content);
const language = stringFile.language;
const subFolder = folder.createFolder(`values-${language}`);
subFolder.createFile("strings.xml", stringFile.content);
}
SpreadsheetApp.getUi().alert("Translations created and uploaded to Drive.");
}
function constructTranslation(values) {
const stringFile = {};
let exportString = '<?xml version="1.0" encoding="UTF-8"?>' + "\n";
exportString += "<resources>\n";
for (const [key, value] of Object.entries(values.texts)) {
exportString += "\t"+'<string name="'+key+'">'+value+'</string>' + "\n";
}
exportString += "</resources>";
stringFile["language"] = values.language;
stringFile["content"] = exportString;
return stringFile;
}
/**
* Returns the array of Keys
*/
function getHeaders(sheet) {
const headersRange = sheet.getRange(1, 2, 1, sheet.getMaxColumns());
const headers = headersRange.getValues()[0];
const keys = [];
for (let i = 0; i < headers.length; i++) {
const key = headers[i];
if (key.length > 0) {
keys.push(key);
} else {
break;
}
}
return keys;
}
function getDataRange(sheet) {
const dataRange = sheet.getRange(2, 2, sheet.getMaxRows(), sheet.getMaxColumns());
const headers = getHeaders(sheet);
return getValues(dataRange.getValues(), headers);
}
/**
* Returns an array of values, where each value is of the form:
* {
* "language" = "en"
* "texts": {
* "key1": "value1",
* "key2": "value2",
* }
* }
*/
function getValues(data, keys) {
const values = [];
// Loop for every language
for (let i = 0; i < data.length; ++i) {
const value = {
"texts": {}
};
let hasData = false;
if (data[i][0].length == 0) {
// If empty, break out of the loop. This means that there are no more Languages to process
break;
}
for (let j = 0; j < data[i].length; j++) {
const content = data[i][j];
if (content.length == 0) {
// If empty, break out of the loop. This means that there are no more Keys to process
break;
}
if (j == 0) {
value["language"]= content;
} else {
value.texts[keys[j]] = content;
}
hasData = true;
}
if (hasData) {
values.push(value);
}
}
return values;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment