CSV Export for DataTable

pull/41/head
cagataycivici 2019-07-09 16:21:42 +03:00
parent 938462c667
commit b8aaea74ff
2 changed files with 94 additions and 3 deletions

View File

@ -216,6 +216,14 @@ export default {
rowHover: {
type: Boolean,
default: false
},
csvSeparator: {
type: String,
default: ','
},
exportFilename: {
type: String,
default: 'download'
}
},
data() {
@ -738,6 +746,80 @@ export default {
}
this.$emit('update:selection', _selection);
},
exportCSV(options) {
let data = this.processedData;
let csv = '\ufeff';
if (options && options.selectionOnly) {
data = this.selection || [];
}
//headers
for (let i = 0; i < this.columns.length; i++) {
let column = this.columns[i];
if (column.exportable !== false && column.field) {
csv += '"' + (column.header || column.field) + '"';
if (i < (this.columns.length - 1)) {
csv += this.csvSeparator;
}
}
}
//body
data.forEach((record, i) => {
csv += '\n';
for (let i = 0; i < this.columns.length; i++) {
let column = this.columns[i];
if (column.exportable !== false && column.field) {
let cellData = ObjectUtils.resolveFieldData(record, column.field);
if (cellData != null) {
if (this.exportFunction) {
cellData = this.exportFunction({
data: cellData,
field: column.field
});
}
else
cellData = String(cellData).replace(/"/g, '""');
}
else
cellData = '';
csv += '"' + cellData + '"';
if (i < (this.columns.length - 1)) {
csv += this.csvSeparator;
}
}
}
});
let blob = new Blob([csv], {
type: 'text/csv;charset=utf-8;'
});
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, this.exportFilename + '.csv');
}
else {
let link = document.createElement("a");
link.style.display = 'none';
document.body.appendChild(link);
if (link.download !== undefined) {
link.setAttribute('href', URL.createObjectURL(blob));
link.setAttribute('download', this.exportFilename + '.csv');
link.click();
}
else {
csv = 'data:text/csv;charset=utf-8,' + csv;
window.open(encodeURI(csv));
}
document.body.removeChild(link);
}
}
},
computed: {

View File

@ -5,13 +5,17 @@
<div class="content-section introduction">
<div class="feature-intro">
<h1>DataTable - Export</h1>
<p>DataTable can export its data to CSV format..</p>
<p>DataTable can export its data to CSV format.</p>
</div>
</div>
<div class="content-section implementation">
<h3 class="first">Basic</h3>
<DataTable :value="cars">
<DataTable :value="cars" ref="dt">
<template #header>
<div style="text-align: left">
<Button icon="pi pi-external-link" label="Export" @click="exportCSV($event)" />
</div>
</template>
<Column field="vin" header="Vin"></Column>
<Column field="year" header="Year"></Column>
<Column field="brand" header="Brand"></Column>
@ -38,6 +42,11 @@ export default {
mounted() {
this.carService.getCarsSmall().then(data => this.cars = data);
},
methods: {
exportCSV() {
this.$refs.dt.exportCSV();
}
},
components: {
'DataTableSubMenu': DataTableSubMenu
}