- 安装依赖 "exceljs": "^4.3.0", "file-saver": "^2.0.5", "luckyexcel": "^1.0.1"; 如果不需要导出功能,则不用安装前两个依赖,和export.js
- 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>
//或者 npm run build后dist文件夹下的所有文件复制到项目目录,然后通过相对路径引入
<link rel='stylesheet' href='./plugins/css/pluginsCss.css' />
<link rel='stylesheet' href='./plugins/plugins.css' />
<link rel='stylesheet' href='./css/luckysheet.css' />
<link rel='stylesheet' href='./assets/iconfont/iconfont.css' />
<script src="./plugins/js/plugin.js"></script>
<script src="./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。
- template页面使用 基础的配置
<template>
<div class='detail'>
<div class="head_wrap">
<input style="font-size: 16px" type="file" @change="uploadExcel" />
<select v-model="selected" @change="selectExcel">
<option disabled value="">Choose</option>
<option v-for="option in options" :key="option.text" :value="option.value">{{ option.text }}</option>
</select>
<a href="javascript:void(0)" @click="downloadExcel">下载表格</a>
</div>
<!-- main -->
<div id="luckysheet" class="sheet_wrap"></div>
<div class="mask_show" v-show="isMaskShow">Downloading...</div>
</div>
</template>
<script>
import LuckyExcel from "luckyexcel";
//导入库export.js 这个文件是es6的,不能在普通的HTML文件直接引入js文件(虽然都是js文件,但是有区别,具体请百度es6与es5)!需要把es6转es5才可以直接引入使用!
import { exportExcel } from "../../utils/export";
export default {
name:'Detail',
data() {
return {
selected: "",
options: [
{
text: "Money Manager.xlsx",
value:
"https://minio.cnbabylon.com/public/luckysheet/money-manager-2.xlsx",
},
{
text: "Activity costs tracker.xlsx",
value:
"https://minio.cnbabylon.com/public/luckysheet/Activity%20costs%20tracker.xlsx",
},
{
text: "House cleaning checklist.xlsx",
value:
"https://minio.cnbabylon.com/public/luckysheet/House%20cleaning%20checklist.xlsx",
},
{
text: "Student assignment planner.xlsx",
value:
"https://minio.cnbabylon.com/public/luckysheet/Student%20assignment%20planner.xlsx",
},
{
text: "Credit card tracker.xlsx",
value:
"https://minio.cnbabylon.com/public/luckysheet/Credit%20card%20tracker.xlsx",
},
{
text: "Blue timesheet.xlsx",
value:
"https://minio.cnbabylon.com/public/luckysheet/Blue%20timesheet.xlsx",
},
{
text: "Student calendar (Mon).xlsx",
value:
"https://minio.cnbabylon.com/public/luckysheet/Student%20calendar%20%28Mon%29.xlsx",
},
{
text: "Blue mileage and expense report.xlsx",
value:
"https://minio.cnbabylon.com/public/luckysheet/Blue%20mileage%20and%20expense%20report.xlsx",
},
],
isMaskShow: false,
};
},
mounted() {
// In some cases, you need to use $nextTick
this.$nextTick(() => {
$(function () {
luckysheet.create({
container: "luckysheet", //容器id
title: "工作簿名称", //工作簿名称
lang: "zh", //语言
showinfobar: true, //顶部内容
showtoolbar: false, //工具栏内容
showsheetbar: false, //底部页签
userMenuItem: [
{
url: "www.baidu.com",
icon: '<i class="fa fa-folder" aria-hidden="true"></i>',
name: "我的表格",
},
{
url: "www.baidu.com",
icon: '<i class="fa fa-sign-out" aria-hidden="true"></i>',
name: "退出登陆",
},
],
userInfo:
'<i style="font-size:16px;color:#ff6a00;" class="fa fa-taxi" aria-hidden="true"></i> DDY', //或者 { userImage:'',userName:''}
defaultFontSize: 40,
rowHeaderWidth: 80, //行标题区域的宽度
columnHeaderHeight: 46, //列标题区域的高度
column: 10,
row: 20,
enableAddRow: false, //添加行
enableAddBackTop: false, //回到顶部
myFolderUrl: "www.baidu.com", //左上角<返回按钮的链接
functionButton:'<button id="">下载</button>', //右上角功能按钮
sheetFormulaBar: true, //是否显示公式栏 值
showtoolbarConfig: {
undoRedo: false, //撤销重做,注意撤消重做是两个按钮,由这一个配置决定显示还是隐藏
paintFormat: false, //格式刷
currencyFormat: false, //货币格式
percentageFormat: false, //百分比格式
numberDecrease: false, // '减少小数位数'
numberIncrease: false, // '增加小数位数
moreFormats: false, // '更多格式'
font: false, // '字体'
fontSize: false, // '字号大小'
bold: false, // '粗体 (Ctrl+B)'
italic: false, // '斜体 (Ctrl+I)'
strikethrough: false, // '删除线 (Alt+Shift+5)'
underline: false, // '下划线 (Alt+Shift+6)'
textColor: false, // '文本颜色'
fillColor: false, // '单元格颜色'
border: false, // '边框'
mergeCell: false, // '合并单元格'
horizontalAlignMode: false, // '水平对齐方式'
verticalAlignMode: false, // '垂直对齐方式'
textWrapMode: false, // '换行方式'
textRotateMode: false, // '文本旋转方式'
image: false, // '插入图片'
link: false, // '插入链接'
chart: false, // '图表'(图标隐藏,但是如果配置了chart插件,右击仍然可以新建图表)
postil: false, //'批注'
pivotTable: false, //'数据透视表'
function: false, // '公式'
frozenMode: false, // '冻结方式'
sortAndFilter: false, // '排序和筛选'
conditionalFormat: false, // '条件格式'
dataVerification: false, // '数据验证'
splitColumn: false, // '分列'
screenshot: false, // '截图'
findAndReplace: false, // '查找替换'
protection: false, // '工作表保护'
print: false, // '打印'
},
showsheetbarConfig: {
add: false, //新增sheet
menu: false, //sheet管理菜单
sheet: false, //sheet页显示
},
sheetRightClickConfig: {
delete: false, // 删除
copy: false, // 复制
rename: false, //重命名
color: false, //更改颜色
hide: false, //隐藏,取消隐藏
move: false, //向左移,向右移
},
showstatisticBarConfig: {
count: false, // 计数栏
view: false, // 打印视图
zoom: false, // 缩放
},
cellRightClickConfig: {
copy: false, // 复制
copyAs: false, // 复制为
paste: false, // 粘贴
insertRow: false, // 插入行
insertColumn: false, // 插入列
deleteRow: false, // 删除选中行
deleteColumn: false, // 删除选中列
deleteCell: false, // 删除单元格
hideRow: false, // 隐藏选中行和显示选中行
hideColumn: false, // 隐藏选中列和显示选中列
rowHeight: false, // 行高
columnWidth: false, // 列宽
clear: false, // 清除内容
matrix: false, // 矩阵操作选区
sort: false, // 排序选区
filter: false, // 筛选选区
chart: false, // 图表生成
image: false, // 插入图片
link: false, // 插入链接
data: false, // 数据验证
cellFormat: false, // 设置单元格格式
},
hook:{ //配置各种钩子函数,见官网
cellMousedownBefore:function(operate){
// console.info(operate)
},
cellMousedown:function(operate){
// console.info(operate)
return false //不能编辑操作
},
updated:function(operate){
// console.info(operate)
},
cellUpdateBefore:function(r,c,value,isRefresh){
//console.info('cellUpdateBefore',r,c,value,isRefresh)
return false //不能编辑操作
},
cellUpdated:function(r,c,oldValue, newValue, isRefresh){
// console.info('cellUpdated',r,c,oldValue, newValue, isRefresh)
},
},
});
});
});
},
methods: {
uploadExcel(evt) {
const files = evt.target.files;
if (files == null || files.length == 0) {
alert("No files wait for import");
return;
}
let name = files[0].name;
let suffixArr = name.split("."),
suffix = suffixArr[suffixArr.length - 1];
if (suffix != "xlsx") {
alert("Currently only supports the import of xlsx files");
return;
}
LuckyExcel.transformExcelToLucky(
files[0],
function (exportJson, luckysheetfile) {
if (exportJson.sheets == null || exportJson.sheets.length == 0) {
alert(
"Failed to read the content of the excel file, currently does not support xls files!"
);
return;
}
luckysheet.destroy();
luckysheet.create({
container: "luckysheet", //luckysheet is the container id
showinfobar: false,
data: exportJson.sheets,
title: exportJson.info.name,
userInfo: exportJson.info.name.creator,
});
}
);
},
selectExcel(evt) {
const value = this.selected;
const name = evt.target.options[evt.target.selectedIndex].innerText;
if (value == "") {
return;
}
this.isMaskShow = true;
LuckyExcel.transformExcelToLuckyByUrl(
value,
name,
(exportJson, luckysheetfile) => {
if (exportJson.sheets == null || exportJson.sheets.length == 0) {
alert("Failed to read the content of the excel file, currently does not support xls files!");
return;
}
this.isMaskShow = false;
luckysheet.destroy();
luckysheet.create({
container: "luckysheet", //luckysheet is the container id
showinfobar: false,
data: exportJson.sheets,
title: exportJson.info.name,
userInfo: exportJson.info.name.creator,
});
}
);
},
downloadExcel() {
exportExcel(luckysheet.getAllSheets(), "下载");
},
},
};
</script>
<style lang="scss" scoped>
.head_wrap{
position: absolute;
top: 0
}
.sheet_wrap{
position: absolute;
width: 100%;
left: 0px;
top: 30px;
bottom: 0px;
}
.mask_show{
position: absolute;
z-index: 1000000;
left: 0px;
top: 0px;
bottom: 0px;
right: 0px;
background: rgba(255, 255, 255, 0.8);
text-align: center;
font-size: 40px;
align-items: center;
justify-content: center;
display: flex;
}
</style>
- utils里面加入该export.js 用于导出excel
// import { createCellPos } from './translateNumToLetter'
const Excel = require('exceljs')
import FileSaver from 'file-saver'
export var testaaa = function (){
console.log("...");
}
export var 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
}
[详情参照原文链接: Luckysheet文档 (gitee.io)]
网友评论