xlsx.js的使用
为什么要用xlsx?
现在前端可惨,许多事都要做了。。。。读取excel的数据,抛弃了以前的上传一个excel文件到后台解析,直接改用了前端读取excel中的数据转成一个数组对象转数据给后台,那没办法,搞吧
安装
1 | npm i xlsx -S |
读取数据
1 | XLSX.read(ArrayBuffer,配置项) |
ArrayBuffer如何来? 参考以下链接: 参考链接:https://zhuanlan.zhihu.com/p/354707440
JS 文件base64、File、Blob、ArrayBuffer互转
1. file对象转base64
1 | let reader = new FileReader(); |
2. base64 转成blob 上传
1 | function dataURItoBlob(dataURI) { |
3. blob 转成ArrayBuffer
1 | let blob = new Blob([1,2,3,4]) |
4. buffer 转成blob
1 | let blob = new Blob([buffer]) |
5. base64 转 file
1 | const base64ConvertFile = function (urlData, filename) { // 64转file |
6. 文件转ArrayBuffer
1 | function toBuffer(file, func) { |
文件转ArrayBuffer? 一个一个转吧
1 | const xlsx = require('xlsx'); |
写入数据
1 | function downloadExcel() { |
参考链接:https://www.npmjs.com/package/xlsx

有样式
官方文档请参考: https://www.npmjs.com/package/xlsx-style
参考网址: https://blog.csdn.net/Yuoliku/article/details/109214337
安装xlsx-style
1 | npm i xlsx-style -S |
修改xlsx-style源码报错
1 | 在\node_modules\xlsx-style\dist\cpexcel.js |
配置参考代码
参考网站:https://blog.csdn.net/qq_42440043/article/details/121974854
常用样式配置
| Style Attribute | Sub Attributes | Values |
|---|---|---|
| fill | patternType | "solid" or "none" |
| fgColor | COLOR_SPEC |
|
| bgColor | COLOR_SPEC |
|
| font | name | "Calibri" // default |
| sz | "11" // font size in points |
|
| color | COLOR_SPEC |
|
| bold | `true | |
| underline | `true | |
| italic | `true | |
| strike | `true | |
| outline | `true | |
| shadow | `true | |
| vertAlign | `true | |
| numFmt | "0" // integer index to built in formats, see StyleBuilder.SSF property |
|
"0.00%" // string matching a built-in format, see StyleBuilder.SSF |
||
"0.0%" // string specifying a custom format |
||
"0.00%;\\(0.00%\\);\\-;@" // string specifying a custom format, escaping special characters |
||
"m/dd/yy" // string a date format using Excel’s format notation |
||
| alignment | vertical | `”bottom” |
| horizontal | `”bottom” | |
| wrapText | `true | |
| readingOrder | 2 // for right-to-left |
|
| textRotation | Number from 0 to 180 or 255 (default is 0) |
|
90 is rotated up 90 degrees |
||
45 is rotated up 45 degrees |
||
135 is rotated down 45 degrees |
||
180 is rotated down 180 degrees |
||
255 is special, aligned vertically |
||
| border | top | { style: BORDER_STYLE, color: COLOR_SPEC } |
| bottom | { style: BORDER_STYLE, color: COLOR_SPEC } |
|
| left | { style: BORDER_STYLE, color: COLOR_SPEC } |
|
| right | { style: BORDER_STYLE, color: COLOR_SPEC } |
|
| diagonal | { style: BORDER_STYLE, color: COLOR_SPEC } |
|
| diagonalUp | `true | |
| diagonalDown | `true |
合并单元格时,如A1-C1合并成一个单元格时,只需要对A1设置样式即可
1 | <button @click="downloadExcel">下载</button> |

给每个单元格添加样式
1 | for (const i in ws) { |
- 本文标题:xlsx.js的使用
- 本文作者:邵预鸿
- 创建时间:2022-05-16 16:52:26
- 本文链接:/images/logo.jpg2022/05/16/xlsx-js的使用/
- 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!