Skip to content

Instantly share code, notes, and snippets.

@the-paulus
Created April 15, 2017 21:08
Show Gist options
  • Save the-paulus/396f7010a7963ecaad4700ff63563971 to your computer and use it in GitHub Desktop.
Save the-paulus/396f7010a7963ecaad4700ff63563971 to your computer and use it in GitHub Desktop.
Google Sheet script that will convert cells A2:D1000 into a downloadable XML file.
function doGet() {
// The sheet that contains the category information.
var categoryDataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Categories");
// The first row of the sheet that contains the categories' name, description, parent, banner image, and list image.
var categoryAttributes = categoryDataSheet.getRange("A1:D1").getValues();
// Range of rows and columns that contain the category information.
var categoryData = categoryDataSheet.getRange("A2:D1000").getValues();
// XML document object.
var document = XmlService.createDocument();
// Root element of the XML output.
var root = XmlService.createElement('manufacturers');
// variable that holds the generated XML document.
var xmlOutput;
for(var i = 0; i < categoryData.length; i++) {
if(!isEnd(categoryData[i])) {
// Begin category tag.
var category = XmlService.createElement('category');
for(var j = 0; j < categoryData[i].length; j++) {
var tag = categoryAttributes[0][j];
var text = categoryData[i][j];
var categoryAttribute = XmlService.createElement(tag);
if(tag == "description") {
categoryAttribute.addContent(XmlService.createCdata(text))
} else {
categoryAttribute.setText(text);
}
category.addContent(categoryAttribute);
}
root.addContent(category);
} else {
break;
}
}
// Put everything together and output it.
document.addContent(root);
xmlOutput = XmlService.getPrettyFormat().format(document);
Logger.log(xmlOutput);
return ContentService.createTextOutput(xmlOutput).downloadAsFile("categories.xml");
}
function isEnd(row) {
for(var i = 0; i < row.length; i++) {
if(row[i] != "") {
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment