一、场景
在实现Excel文件导入时,领导要求实现在前端导入文件后,不调用后端的接口,而是直接显示excel文件的内容,等待用户修改完以后,再调用后端接口进行文件的提交。在这种应用场景下,使用了LuckySheet进行改功能的实现。
附上LuckySheet官网地址
二、Vue3中的基本使用
1、引入luckySheet
引入方式有两种,分别是CDN引入与本地引入,下面都会做介绍:
(1)CDN引入
在你的index.html中复制下面这段代码,实现CDN引入。- <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet/dist/plugins/css/pluginsCss.css' />
- <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet/dist/plugins/plugins.css' />
- <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet/dist/css/luckysheet.css' />
- <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet/dist/assets/iconfont/iconfont.css' />
- <script src="https://cdn.jsdelivr.net/npm/luckysheet/dist/plugins/js/plugin.js"></script>
- <script src="https://cdn.jsdelivr.net/npm/luckysheet/dist/luckysheet.umd.js"></script>
复制代码 注意,https://cdn.jsdelivr.net/npm/luckysheet/dist/luckysheet.umd.js这个路径意思是会拉取到最新的luckysheet代码,但是如果Luckysheet刚刚发布,jsdelivr网站可能还没来得及从npm上同步过去,故而使用这个路径还是会拉到上一个版本,我们推荐您直接指定最新版本。
想要指定Luckysheet版本,请在所有的CDN依赖文件后面加上版本号,如:https://cdn.jsdelivr.net/npm/luckysheet@2.1.12/dist/luckysheet.umd.js。- 如何知道最新版本是哪一版?查看最新 <a href="https://github.com/dream-num/Luckysheet/releases" rel="external nofollow" target="_blank">release记录 (opens new window)</a>或者 <a href="https://github.com/dream-num/Luckysheet/blob/master/package.json" rel="external nofollow" target="_blank">package.json (opens new window)</a>的[code]version
复制代码 字段。[/code]如果不方便访问 jsdelivr.net,还可以采用本地方式引入。
(2)本地引入
本地引入是将CDN引入的文件都放在本地文件中
第一步:克隆或者下载下面的代码- git clone https://github.com/dream-num/Luckysheet.git
复制代码 第二步:安装依赖- npm install
- npm install gulp -g
复制代码 第三步:运行查看运行效果
第四步:打包第五步:本地引入
打包执行成功后,在文件夹目录下会出现dis文件夹,如下图所示:
把dist文件夹中的代码全部复制粘贴到你项目的public文件夹中,index.html文件除外。
在你项目的index.html文件中引入如下代码,如果你复制的位置是其他地方,需要用绝对路径引入这些文件。- <link rel='stylesheet' href='./public/plugins/css/pluginsCss.css' />
- <link rel='stylesheet' href='./public/plugins/plugins.css' />
- <link rel='stylesheet' href='./public/css/luckysheet.css' />
- <link rel='stylesheet' href='./public/assets/iconfont/iconfont.css' />
- <script src="./public/plugins/js/plugin.js"></script>
- <script src="./public/luckysheet.umd.js"></script>
复制代码 2、在页面中进行展示
(1)指定一个容器
- <div id="luckysheet" class="luckysheet-wrap"></div>
- <style scoped>
- .luckysheet-wrap {
- margin: 0px;
- padding: 0px;
- position: absolute;
- width: 100%;
- height: 100%;
- left: 0px;
- top: 0px;
- }
- </style>
复制代码 (2)创建一个表格
- onMounted(() => {
- //如果这里luckysheet.create报错
- //请使用 window.luckysheet.create
- luckysheet.create({
- container: 'luckysheet'//这里需要和容器的id名称一致
- })
- })
复制代码 三、Excel文件的导入与导出
1、导入Excel文件
安装luckyexcel- npm install luckyexcel --save
复制代码 准备一个导入按钮,也可以使用elementUI的导入组件
这边准备了一个导入按钮- <input id="uploadBtn" type="file" @change="loadExcel" />
复制代码- const loadExcel = (evt) => {
- const files = evt.target.files
- if (files == null || files.length == 0) {
- alert('请上传文件')
- return
- }
- let name = files[0].name
- let suffixArr = name.split('.'),
- suffix = suffixArr[suffixArr.length - 1]
- if (suffix != 'xlsx') {
- alert('只能导入xlsx文件格式的Excel')
- return
- }
- LuckyExcel.transformExcelToLucky(files[0], function (exportJson, luckysheetfile) {
- if (exportJson.sheets == null || exportJson.sheets.length == 0) {
- alert('导入失败!')
- return
- }
- window.luckysheet.destroy()
- window.luckysheet.create({
- container: 'luckysheet', //容器的Id
- showinfobar: false,
- data: exportJson.sheets,
- title: exportJson.info.name,
- userInfo: exportJson.info.name.creator
- })
- })
- }
复制代码 2、导出Excel
导出需要用到excejs和file-saver- //安装exceljs
- npm i exceljs --save
- //安装文件保存的库
- npm i file-saver --save
复制代码 这里附上LuckySheet官网提供的导出函数,直接在项目中新建export.js使用- // import { createCellPos } from './translateNumToLetter'
- import Excel from 'exceljs'
- import FileSaver from 'file-saver'
- const exportExcel = function(luckysheet, value) {
- // 参数为luckysheet.getluckysheetfile()获取的对象
- // 1.创建工作簿,可以为工作簿添加属性
- const workbook = new Excel.Workbook()
- // 2.创建表格,第二个参数可以配置创建什么样的工作表
- if (Object.prototype.toString.call(luckysheet) === '[object Object]') {
- luckysheet = [luckysheet]
- }
- luckysheet.forEach(function(table) {
- if (table.data.length === 0) return true
- // ws.getCell('B2').fill = fills.
- const worksheet = workbook.addWorksheet(table.name)
- const merge = (table.config && table.config.merge) || {}
- const borderInfo = (table.config && table.config.borderInfo) || {}
- // 3.设置单元格合并,设置单元格边框,设置单元格样式,设置值
- setStyleAndValue(table.data, worksheet)
- setMerge(merge, worksheet)
- setBorder(borderInfo, worksheet)
- return true
- })
- // return
- // 4.写入 buffer
- const buffer = workbook.xlsx.writeBuffer().then(data => {
- // console.log('data', data)
- const blob = new Blob([data], {
- type: 'application/vnd.ms-excel;charset=utf-8'
- })
- console.log("导出成功!")
- FileSaver.saveAs(blob, `${value}.xlsx`)
- })
- return buffer
- }
- var setMerge = function(luckyMerge = {}, worksheet) {
- const mergearr = Object.values(luckyMerge)
- mergearr.forEach(function(elem) {
- // elem格式:{r: 0, c: 0, rs: 1, cs: 2}
- // 按开始行,开始列,结束行,结束列合并(相当于 K10:M12)
- worksheet.mergeCells(
- elem.r + 1,
- elem.c + 1,
- elem.r + elem.rs,
- elem.c + elem.cs
- )
- })
- }
- var setBorder = function(luckyBorderInfo, worksheet) {
- if (!Array.isArray(luckyBorderInfo)) return
- // console.log('luckyBorderInfo', luckyBorderInfo)
- luckyBorderInfo.forEach(function(elem) {
- // 现在只兼容到borderType 为range的情况
- // console.log('ele', elem)
- if (elem.rangeType === 'range') {
- let border = borderConvert(elem.borderType, elem.style, elem.color)
- let rang = elem.range[0]
- // console.log('range', rang)
- let row = rang.row
- let column = rang.column
- for (let i = row[0] + 1; i < row[1] + 2; i++) {
- for (let y = column[0] + 1; y < column[1] + 2; y++) {
- worksheet.getCell(i, y).border = border
- }
- }
- }
- if (elem.rangeType === 'cell') {
- // col_index: 2
- // row_index: 1
- // b: {
- // color: '#d0d4e3'
- // style: 1
- // }
- const { col_index, row_index } = elem.value
- const borderData = Object.assign({}, elem.value)
- delete borderData.col_index
- delete borderData.row_index
- let border = addborderToCell(borderData, row_index, col_index)
- // console.log('bordre', border, borderData)
- worksheet.getCell(row_index + 1, col_index + 1).border = border
- }
- // console.log(rang.column_focus + 1, rang.row_focus + 1)
- // worksheet.getCell(rang.row_focus + 1, rang.column_focus + 1).border = border
- })
- }
- var setStyleAndValue = function(cellArr, worksheet) {
- if (!Array.isArray(cellArr)) return
- cellArr.forEach(function(row, rowid) {
- row.every(function(cell, columnid) {
- if (!cell) return true
- let fill = fillConvert(cell.bg)
- let font = fontConvert(
- cell.ff,
- cell.fc,
- cell.bl,
- cell.it,
- cell.fs,
- cell.cl,
- cell.ul
- )
- let alignment = alignmentConvert(cell.vt, cell.ht, cell.tb, cell.tr)
- let value = ''
- if (cell.f) {
- value = { formula: cell.f, result: cell.v }
- } else if (!cell.v && cell.ct && cell.ct.s) {
- // xls转为xlsx之后,内部存在不同的格式,都会进到富文本里,即值不存在与cell.v,而是存在于cell.ct.s之后
- // value = cell.ct.s[0].v
- cell.ct.s.forEach(arr => {
- value += arr.v
- })
- } else {
- value = cell.v
- }
- // style 填入到_value中可以实现填充色
- let letter = createCellPos(columnid)
- let target = worksheet.getCell(letter + (rowid + 1))
- // console.log('1233', letter + (rowid + 1))
- for (const key in fill) {
- target.fill = fill
- break
- }
- target.font = font
- target.alignment = alignment
- target.value = value
- return true
- })
- })
- }
- var fillConvert = function(bg) {
- if (!bg) {
- return {}
- }
- // const bgc = bg.replace('#', '')
- let fill = {
- type: 'pattern',
- pattern: 'solid',
- fgColor: { argb: bg.replace('#', '') }
- }
- return fill
- }
- var fontConvert = function(
- ff = 0,
- fc = '#000000',
- bl = 0,
- it = 0,
- fs = 10,
- cl = 0,
- ul = 0
- ) {
- // luckysheet:ff(样式), fc(颜色), bl(粗体), it(斜体), fs(大小), cl(删除线), ul(下划线)
- const luckyToExcel = {
- 0: '微软雅黑',
- 1: '宋体(Song)',
- 2: '黑体(ST Heiti)',
- 3: '楷体(ST Kaiti)',
- 4: '仿宋(ST FangSong)',
- 5: '新宋体(ST Song)',
- 6: '华文新魏',
- 7: '华文行楷',
- 8: '华文隶书',
- 9: 'Arial',
- 10: 'Times New Roman ',
- 11: 'Tahoma ',
- 12: 'Verdana',
- num2bl: function(num) {
- return num === 0 ? false : true
- }
- }
- // 出现Bug,导入的时候ff为luckyToExcel的val
- let font = {
- name: typeof ff === 'number' ? luckyToExcel[ff] : ff,
- family: 1,
- size: fs,
- color: { argb: fc.replace('#', '') },
- bold: luckyToExcel.num2bl(bl),
- italic: luckyToExcel.num2bl(it),
- underline: luckyToExcel.num2bl(ul),
- strike: luckyToExcel.num2bl(cl)
- }
- return font
- }
- var alignmentConvert = function(
- vt = 'default',
- ht = 'default',
- tb = 'default',
- tr = 'default'
- ) {
- // luckysheet:vt(垂直), ht(水平), tb(换行), tr(旋转)
- const luckyToExcel = {
- vertical: {
- 0: 'middle',
- 1: 'top',
- 2: 'bottom',
- default: 'top'
- },
- horizontal: {
- 0: 'center',
- 1: 'left',
- 2: 'right',
- default: 'left'
- },
- wrapText: {
- 0: false,
- 1: false,
- 2: true,
- default: false
- },
- textRotation: {
- 0: 0,
- 1: 45,
- 2: -45,
- 3: 'vertical',
- 4: 90,
- 5: -90,
- default: 0
- }
- }
- let alignment = {
- vertical: luckyToExcel.vertical[vt],
- horizontal: luckyToExcel.horizontal[ht],
- wrapText: luckyToExcel.wrapText[tb],
- textRotation: luckyToExcel.textRotation[tr]
- }
- return alignment
- }
- var borderConvert = function(borderType, style = 1, color = '#000') {
- // 对应luckysheet的config中borderinfo的的参数
- if (!borderType) {
- return {}
- }
- const luckyToExcel = {
- type: {
- 'border-all': 'all',
- 'border-top': 'top',
- 'border-right': 'right',
- 'border-bottom': 'bottom',
- 'border-left': 'left'
- },
- style: {
- 0: 'none',
- 1: 'thin',
- 2: 'hair',
- 3: 'dotted',
- 4: 'dashDot', // 'Dashed',
- 5: 'dashDot',
- 6: 'dashDotDot',
- 7: 'double',
- 8: 'medium',
- 9: 'mediumDashed',
- 10: 'mediumDashDot',
- 11: 'mediumDashDotDot',
- 12: 'slantDashDot',
- 13: 'thick'
- }
- }
- let template = {
- style: luckyToExcel.style[style],
- color: { argb: color.replace('#', '') }
- }
- let border = {}
- if (luckyToExcel.type[borderType] === 'all') {
- border['top'] = template
- border['right'] = template
- border['bottom'] = template
- border['left'] = template
- } else {
- border[luckyToExcel.type[borderType]] = template
- }
- // console.log('border', border)
- return border
- }
- function addborderToCell(borders, row_index, col_index) {
- let border = {}
- const luckyExcel = {
- type: {
- l: 'left',
- r: 'right',
- b: 'bottom',
- t: 'top'
- },
- style: {
- 0: 'none',
- 1: 'thin',
- 2: 'hair',
- 3: 'dotted',
- 4: 'dashDot', // 'Dashed',
- 5: 'dashDot',
- 6: 'dashDotDot',
- 7: 'double',
- 8: 'medium',
- 9: 'mediumDashed',
- 10: 'mediumDashDot',
- 11: 'mediumDashDotDot',
- 12: 'slantDashDot',
- 13: 'thick'
- }
- }
- // console.log('borders', borders)
- for (const bor in borders) {
- // console.log(bor)
- if (borders[bor].color.indexOf('rgb') === -1) {
- border[luckyExcel.type[bor]] = {
- style: luckyExcel.style[borders[bor].style],
- color: { argb: borders[bor].color.replace('#', '') }
- }
- } else {
- border[luckyExcel.type[bor]] = {
- style: luckyExcel.style[borders[bor].style],
- color: { argb: borders[bor].color }
- }
- }
- }
- return border
- }
- function createCellPos(n) {
- let ordA = 'A'.charCodeAt(0)
- let ordZ = 'Z'.charCodeAt(0)
- let len = ordZ - ordA + 1
- let s = ''
- while (n >= 0) {
- s = String.fromCharCode((n % len) + ordA) + s
- n = Math.floor(n / len) - 1
- }
- return s
- }
- export {
- exportExcel
- }
复制代码 在页面中引入export.js文件- import { exportExcel } from './export'
复制代码 在页面中使用下面这句代码进行导出- exportExcel(luckysheet.getAllSheets(), '导出的文件名字')
复制代码 四、注意事项
在导出文件时,如果需要将导出的数据通过接口传输给后端,需要进行文件格式的转换,以file为例。- //获取buffer的
- workbook.xlsx.writeBuffer()
- .then((arrayBuffer) => {
- const blob = new Blob(arrayBuffer, {
- //导出为xlsx文件格式
- type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
- });
- //转为file格式
- let file = new File([blob], '导出.xlsx', {type: blob.type});
- /**
- 这里书写接口上传代码
- */
- }).catch(err=>{
- dialogVisible.value = false
- })
复制代码 LuckySheet现在升级为Univer Docs,如果需要使用Univer Docs进行展示excel,可以参考另一篇文章进行了解。
以上就是Vue3项目中通过LuckySheet实现Excel在线编辑的详细内容,更多关于Vue3 LuckySheet在线编辑Excel的资料请关注脚本之家其它相关文章!
来源:https://www.jb51.net/javascript/339448a6b.htm
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |