tdc-js-modules
Version:
77 lines (69 loc) • 2.72 kB
text/typescript
/**
*
* @param colums: Array of type ColumnType that describes the shape of a column in a DataTable.
* @param records: Arreglo de información; las llaves
* @param fileName: Name of the file to be exported.
*/
import { ColumnType } from '../@types/ColumnT';
import {getValueFromSelector} from "./getObjectValueFromSelector";
const exportToExcel = (columns: ColumnType[], records: any[], fileName: string, ext?: string) => {
let sTable = '<table>';
sTable += '<thead>';
sTable += '<tr>';
columns.forEach(col => {
if (col.exportable) {
sTable += '<th>' + col.name + '</th>';
}
});
sTable += '</tr>';
sTable += '</thead>';
sTable += '<tbody>';
for (let i in records) {
let record = records[i];
sTable += '<tr>';
columns.forEach(col => {
if (col.exportable && col.exportableFunction) {
sTable += '<td>' + col.exportableFunction(record) + '</td>';
} else if (col.exportable) {
const value = getValueFromSelector(col.selector, record)
sTable += '<td>' + value + '</td>';
} /*else {
sTable += '<td></td>';
}*/
});
sTable += '</tr>';
}
sTable += '</tbody>';
sTable += '</table>';
let uri = 'data:application/vnd.ms-excel;base64,',
template =
'<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>',
base64 = function(s: any) {
return window.btoa(unescape(encodeURIComponent(s)));
},
format = function(s: any, c: any) {
return s.replace(/{(\w+)}/g, function(m: any, p: any) {
return c[p];
});
};
let ctx = {
worksheet: fileName,
table: sTable,
},
href = uri + base64(format(template, ctx));
let extention: string = '.xls';
extention = ext? ext: extention;
if (window.navigator.msSaveBlob) {
const blob = new Blob([format(template, ctx)], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;',
});
window.navigator.msSaveOrOpenBlob(blob, fileName + extention);
} else {
let anc = document.createElement('a');
anc.setAttribute('href', href);
anc.setAttribute('download', fileName + extention);
document.body.appendChild(anc);
anc.click();
}
};
export { exportToExcel };