I am using the following code to create excel file data from JSON object and then download it on the click of a button.
getExcelFile: function() {
testJson = validation_data;
testTypes = {
"name": "String",
"city": "String",
"country": "String",
"birthdate": "String",
"amount": "Number"
};
emitXmlHeader = function() {
return '<?xml version="1.0"?>\n' +
'<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">\n' +
'<ss:Worksheet ss:Name="Sheet1">\n' +
'<ss:Table>\n\n';
};
emitXmlFooter = function() {
return '\n</ss:Table>\n' +
'</ss:Worksheet>\n' +
'</ss:Workbook>\n';
};
jsonToSsXml = function(jsonObject) {
var row;
var col;
var xml;
var data = typeof jsonObject != "object"
? JSON.parse(jsonObject)
: jsonObject;
xml = emitXmlHeader();
for (row = 0; row < data.length; row++) {
xml += '<ss:Row>\n';
for (col in data[row]) {
xml += ' <ss:Cell>\n';
xml += ' <ss:Data ss:Type="' + testTypes[col] + '">';
xml += data[row][col] + '</ss:Data>\n';
xml += ' </ss:Cell>\n';
}
xml += '</ss:Row>\n';
}
xml += emitXmlFooter();
return xml;
};
download = function(content, filename, contentType) {
if (!contentType)
contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
var a = document.getElementById('test');
var blob = new Blob([content], {
'type': contentType
});
a.href = window.URL.createObjectURL(blob);
a.download = filename;
};
download(jsonToSsXml(testJson), 'validation_data.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
}
But the file created doesn't open in Microsoft Office 2007 and gives the error 'File may be corrupt'. Please help.