使用Handsontable导出CSV表格并替换单元格自定义值
在Handsontable导出CSV时替换单元格值的解决方案
嘿,我来帮你搞定这个导出时替换单元格值的需求!你需要在导出CSV的时候,把表格里默认生成的A1、A2、B1、B2替换成temp对象里对应的映射值,其实只需要在导出前处理好要导出的数据,再传给导出插件就行。
修改后的完整代码
<div id="example1" class="hot handsontable htRowHeaders htColumnHeaders"></div> <button id="export-file">导出CSV</button> <script src="https://docs.handsontable.com/pro/1.6.0/bower_components/handsontable-pro/dist/handsontable.full.min.js"></script> <link type="text/css" rel="stylesheet" href="https://docs.handsontable.com/pro/1.6.0/bower_components/handsontable-pro/dist/handsontable.full.min.css"> <script> document.addEventListener("DOMContentLoaded", function() { var temp = {"A1":"first","A2":"second","B1":"third","B2":"fourth"}; var example1 = document.getElementById('example1'); var hot = new Handsontable(example1, { data: Handsontable.helper.createSpreadsheetData(2, 2), colHeaders: true, rowHeaders: true }); var buttons = { file: document.getElementById('export-file') }; var exportPlugin = hot.getPlugin('exportFile'); buttons.file.addEventListener('click', function() { // 关键:处理导出数据,替换成temp中的映射值 const exportData = hot.getData().map((row, rowIndex) => { return row.map((cellValue, colIndex) => { // 生成单元格坐标(比如A1、B2) const colLetter = String.fromCharCode(65 + colIndex); // 0对应A,1对应B... const cellKey = `${colLetter}${rowIndex + 1}`; // 行号从1开始 // 优先用temp中的值,没有则保留原单元格内容 return temp[cellKey] || cellValue; }); }); // 传入处理好的数据进行导出 exportPlugin.downloadFile('csv', { filename: 'MyFile', data: exportData }); }); }); </script>
关键修改点说明
- 在导出按钮的点击事件里,我们先通过
hot.getData()获取表格当前的原始数据 - 遍历每一行每一列,根据行列索引生成对应的单元格坐标(比如第0行第0列对应
A1) - 用生成的坐标去
temp对象里查找对应的替换值,如果存在就用替换值,不存在则保留原内容 - 最后调用
downloadFile时,在配置项里传入处理好的exportData,这样导出的CSV就会是替换后的值啦
内容的提问来源于stack exchange,提问作者Arjun




