Export CSV file in JS
- 2021年10月29日
- 技術情報
This time I would like to share about export a file as CSV format using Javascript HandSonTable. HandSonTable works with many of most popular languages like : React, Angualr, Vue and Javascript.
Then what is HandSonTable? HandSonTable is like data grid spreadsheet designed to hundreds of thousands of cells. HandSonTable is performed with so much features ex: search, sort, filter without delays. Let’s start!
Firstly, we need to do is to import handsontable.full.min.js and handsontable.full.min.css in html. After importing, we can now use HandSonTable. To display HandSonTable, we need to add a new div with id or class name attribute.
Import JS and Css file in header
<script src="https://cdn.jsdelivr.net/npm/handsontable@10.0/dist/handsontable.full.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/handsontable@10.0/dist/handsontable.full.min.css" />
Add new div and download button for export CSV format
<div id="example1"></div>
<div class="controls">
<button id="export-file">Download CSV</button>
</div>
Let’s start JS code!
For use HandSonTable, we must call that two attributes roughly first one is what place we want to append data so we will call our Id named with example1, and second one is how much data display with rows and cols and what kind of data display.
Then to call our id and button using javascript querySelector.
const container = document.querySelector('#example1');
const button = document.querySelector('#export-file');
const hot = new Handsontable(container, {
data: Handsontable.helper.createSpreadsheetData(7, 7),
colHeaders: true,
rowHeaders: true,
hiddenRows: { rows: [1, 3, 5], indicators: true },
hiddenColumns: { columns: [1, 3, 5], indicators: true },
height: 'auto',
licenseKey: 'non-commercial-and-evaluation'
});
To export a file, we can use tabename.getPlugin(‘exportFile’);
After button click action is done, for download the file we can use javascript addEventListener with click property. For downloadFile and fileExtension must be ‘csv’ and fill your desire filename.
button.addEventListener('click', () => {
exportPlugin.downloadFile('csv', {
bom: false,
columnDelimiter: ',',
columnHeaders: false,
exportHiddenColumns: true,
exportHiddenRows: true,
fileExtension: 'csv',
filename: 'Handsontable-CSV-file_[YYYY]-[MM]-[DD]',
mimeType: 'text/csv',
rowDelimiter: '\r\n',
rowHeaders: true
});
});
Hoped you enjoyed reading this!
By Ami
asahi at 2021年10月29日 10:00:00