背景介绍 想写一个html用来打开Excel文件,添加人物,随机抽取人员,输出添加人员后的Excel。
xlsx.js xlsx.js 是一个开源的 JavaScript 库,用于处理 Excel 文件。它可以读取、写入和转换 Excel 文件,支持多种格式(如 .xlsx、.xlsm、.xlsb 等),并且兼容多种浏览器。
引用xlsx.js 首先需要在html的head中引用xlsx.js
1 COPY <script src ="https://cdn.bootcdn.net/ajax/libs/xlsx/0.18.5/xlsx.core.min.js" > </script >
读取文件:
1 2 3 4 5 6 7 COPY <div id ="app" > <h1 > 选择文件:</h1 > <input type ="file" ref ="fileInput" > <button @click ="readFile" > 读取文件</button > <button @click ="writeFile" :disabled ="!jsonData.length" > 写入文件</button > </div >
注意:将获取的file转换为JSON的代码不能写在readfil里,这是因为reader的readAsBinaryString是异步加载,加载完毕会触发一个load事件,所以要写到mounted中
mounted中this.reader.addEventListener('load',()=>{})
监听了load事件,当异步加载完成后触发lambda表达式内的函数。
js脚本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 COPY <script > const app = { data :function ( ){ return { fileInput : '' , reader : new FileReader (), jsonData : [] } }, mounted ( ) { this .reader .addEventListener ('load' , () => { console .log ("read file to XLSX" ) const data = this .reader .result const workbook = XLSX .read (data, { type : 'binary' }) const sheetName = workbook.SheetNames [0 ] const sheet = workbook.Sheets [sheetName] this .jsonData = XLSX .utils .sheet_to_json (sheet) }) }, methods : { readFile ( ) { console .log ('read file' ); const file = this .$refs .fileInput .files [0 ] if (!file) return this .reader .readAsBinaryString (file) }, writeFile ( ) { const sheet = XLSX .utils .json_to_sheet (this .jsonData ) const workbook = XLSX .utils .book_new () XLSX .utils .book_append_sheet (workbook, sheet, 'Sheet1' ) const blob = new Blob ([XLSX .write (workbook, { bookType : 'xlsx' , type : 'array' })], { type : 'application/octet-stream' }) saveAs (blob, 'data.xlsx' ) }, } Vue .createApp (app).mount ('#app' ) </script >
xlxs.js中需要用workbook装sheet表单,sheet表单内存着各行各列的数据。最后封装导出时需要用到FileSaver.js库,使用 FileSaver.js 很简单,只需调用 saveAs() 函数即可。saveAs() 函数需要两个参数:文件的 Blob 对象和文件名。
例如,如果要保存一个文本文件,可以使用以下代码:
1 2 3 4 5 6 COPY import { saveAs } from 'file-saver' function downloadTextFile (text ) { const blob = new Blob ([text], { type : 'text/plain' }) saveAs (blob, 'text-file.txt' ) }
保存xlsx文件:
1 2 3 4 5 6 7 8 9 10 11 COPY import XLSX from 'xlsx' import { saveAs } from 'file-saver' function downloadExcel (data ) { const ws = XLSX .utils .aoa_to_sheet (data) const wb = XLSX .utils .book_new () XLSX .utils .book_append_sheet (wb, ws, 'Sheet1' ) const blob = new Blob ([XLSX .write (wb, { bookType : 'xlsx' , type : 'array' })], { type : 'application/octet-stream' }) saveAs (blob, 'data.xlsx' ) }
上面的代码首先使用 XLSX.utils.aoa_to_sheet() 将数据转换为工作表对象,然后使用 XLSX.utils.book_new() 创建新的工作簿对象。最后,使用 XLSX.utils.book_append_sheet() 将工作表添加到工作簿中,并使用 XLSX.write() 将工作簿转换为二进制数组。然后,将二进制数组包装在 Blob 对象中,并使用 saveAs() 函数将文件保存到用户计算机。
参考
xlsx.js使用教程: https://blog.csdn.net/GFing18/article/details/125523446
xlsx.js官方文档:https://github.com/exceljs/exceljs/blob/HEAD/README_zh.md