联调设备文件

This commit is contained in:
guanj
2026-03-30 09:03:53 +08:00
parent a30379ab01
commit 762965b1e4
11 changed files with 941 additions and 689 deletions

View File

@@ -2,7 +2,7 @@
<template>
<div class="default-main main" :style="{ height: pageHeight.height }">
<div class="main_left">
<DeviceTree @node-click="nodeClick" @init="nodeClick"></DeviceTree>
<DeviceTree @node-click="nodeClick" @deviceTypeChange="deviceTypeChange"></DeviceTree>
</div>
<div class="main_right" v-loading="loading">
<div class="right_nav">
@@ -197,22 +197,25 @@
import DeviceTree from '@/components/tree/govern/deviceTree.vue'
import { mainHeight } from '@/utils/layout'
import { ref, watch, onMounted, onBeforeUnmount, h, inject } from 'vue'
import { ElMessage, ElMessageBox, ElInput } from 'element-plus'
import { ElMessage, ElMessageBox, ElInput, ElSegmented } from 'element-plus'
import {
getFileServiceFileOrDir,
uploadDeviceFile,
reStartDevice,
addDeviceDir,
delDeviceDir
} from '@/api/cs-device-boot/fileService.ts'
delDeviceDir,
listDir,
downloadFileFromFrontr
} from '@/api/cs-device-boot/fileService'
import { defaultAttribute } from '@/components/table/defaultAttribute'
import { Delete, Download, Upload, Plus, Refresh, Search } from '@element-plus/icons-vue'
import popup from './popup.vue'
import mqtt from 'mqtt'
import { useAdminInfo } from '@/stores/adminInfo'
import { passwordConfirm } from '@/api/user-boot/user'
import { downLoadFile } from '@/utils/downloadFile.ts'
defineOptions({
name: 'govern/device/fileService'
name: 'govern/device/fileService/index'
})
const pageHeight = mainHeight(20)
const tableHeight = mainHeight(130)
@@ -220,31 +223,53 @@ const adminInfo = useAdminInfo()
const loading = ref(false)
//nDid
const nDid = ref<string>('')
const devId = ref<string>('')
//当前目录
const activePath = ref<string>('')
//判断是否是根目录
const isRoot = ref<boolean>(true)
//储存所有点击过的目录
const activePathList: any = ref([])
const devConType = ref<string>('')
const deviceTypeChange = (val: any, obj: any) => {
nodeClick(obj)
}
const nodeClick = (e: any) => {
if (e && (e.level == 2 || e.type == 'device')) {
loading.value = true
nDid.value = e.ndid
devId.value = e.id
dirList.value = []
activePathList.value = []
activePath.value = '/'
getFileServiceFileOrDir({ nDid: nDid.value, name: activePath.value, type: 'dir' })
.then((resp: any) => {
if (resp.code == 'A0000') {
dirList.value = resp.data
currentDirList.value = resp.data
activePathList.value = [{ path: activePath.value }]
devConType.value = e.devConType
if (devConType.value == 'CLD') {
listDir({ devId: devId.value, filePath: activePath.value })
.then((resp: any) => {
if (resp.code == 'A0000') {
dirList.value = resp.data
currentDirList.value = resp.data
activePathList.value = [{ path: activePath.value }]
loading.value = false
}
})
.catch(e => {
loading.value = false
}
})
.catch(e => {
loading.value = false
})
})
} else {
getFileServiceFileOrDir({ nDid: nDid.value, name: activePath.value, type: 'dir' })
.then((resp: any) => {
if (resp.code == 'A0000') {
dirList.value = resp.data
currentDirList.value = resp.data
activePathList.value = [{ path: activePath.value }]
loading.value = false
}
})
.catch(e => {
loading.value = false
})
}
}
}
//搜索文件或文件夹
@@ -360,21 +385,41 @@ const handleIntoDir = (row: any) => {
if (activePathList.value.indexOf(obj.name) == -1) {
activePathList.value.push({ path: obj.name })
}
getFileServiceFileOrDir(obj)
.then(res => {
dirList.value = res.data
loading.value = false
currentDirList.value = res.data
activePathList.value.map((item: any, index: any) => {
if (item.path.includes(activePath.value) && item.path.length > activePath.value.length) {
activePathList.value.splice(index, 1)
if (devConType.value == 'CLD') {
listDir({ devId: devId.value, filePath: row.prjDataPath })
.then((resp: any) => {
if (resp.code == 'A0000') {
dirList.value = resp.data
currentDirList.value = resp.data
activePathList.value.map((item: any, index: any) => {
if (item.path.includes(activePath.value) && item.path.length > activePath.value.length) {
activePathList.value.splice(index, 1)
}
})
loading.value = false
}
})
isRoot.value = false
})
.catch(e => {
loading.value = false
})
.catch(e => {
loading.value = false
})
} else {
getFileServiceFileOrDir(obj)
.then(res => {
dirList.value = res.data
loading.value = false
currentDirList.value = res.data
activePathList.value.map((item: any, index: any) => {
if (item.path.includes(activePath.value) && item.path.length > activePath.value.length) {
activePathList.value.splice(index, 1)
}
})
isRoot.value = false
})
.catch(e => {
loading.value = false
})
}
}
//处理导航栏路径
@@ -406,19 +451,38 @@ const handleIntoByPath = async (val: any) => {
}
activePath.value = val.path
loading.value = true
getFileServiceFileOrDir(obj)
.then(res => {
dirList.value = res.data
activePathList.value.map((item: any, index: any) => {
if (item.path.includes(activePath.value) && item.path.length > activePath.value.length) {
activePathList.value.splice(index, 1)
if (devConType.value == 'CLD') {
listDir({ devId: devId.value, filePath: val.path })
.then((resp: any) => {
if (resp.code == 'A0000') {
dirList.value = resp.data
activePathList.value.map((item: any, index: any) => {
if (item.path.includes(activePath.value) && item.path.length > activePath.value.length) {
activePathList.value.splice(index, 1)
}
})
loading.value = false
}
})
loading.value = false
})
.catch(e => {
loading.value = false
})
.catch(e => {
loading.value = false
})
} else {
getFileServiceFileOrDir(obj)
.then(res => {
dirList.value = res.data
activePathList.value.map((item: any, index: any) => {
if (item.path.includes(activePath.value) && item.path.length > activePath.value.length) {
activePathList.value.splice(index, 1)
}
})
loading.value = false
})
.catch(e => {
loading.value = false
})
}
}
const form = ref({
path: ''
@@ -437,26 +501,48 @@ const formRef = ref()
//重新加载当前页面菜单
const reloadCurrentMenu = (msg: string) => {
loading.value = true
getFileServiceFileOrDir({ nDid: nDid.value, name: activePath.value, type: 'dir' })
.then((resp: any) => {
if (resp.code == 'A0000') {
loading.value = false
dirList.value = resp.data
currentDirList.value = resp.data
activePathList.value.map((item: any, index: any) => {
if (item.path.includes(activePath.value) && item.path.length > activePath.value.length) {
activePathList.value.splice(index, 1)
}
})
loading.value = false
if (!msg) return
ElMessage({ message: msg, type: 'success', duration: 5000 })
}
})
.catch(e => {
loading.value = false
})
if (devConType.value == 'CLD') {
listDir({ devId: devId.value, filePath: activePath.value })
.then((resp: any) => {
if (resp.code == 'A0000') {
dirList.value = resp.data
currentDirList.value = resp.data
activePathList.value.map((item: any, index: any) => {
if (item.path.includes(activePath.value) && item.path.length > activePath.value.length) {
activePathList.value.splice(index, 1)
}
})
loading.value = false
if (!msg) return
ElMessage({ message: msg, type: 'success', duration: 5000 })
}
})
.catch(e => {
loading.value = false
})
} else {
getFileServiceFileOrDir({ nDid: nDid.value, name: activePath.value, type: 'dir' })
.then((resp: any) => {
if (resp.code == 'A0000') {
loading.value = false
dirList.value = resp.data
currentDirList.value = resp.data
activePathList.value.map((item: any, index: any) => {
if (item.path.includes(activePath.value) && item.path.length > activePath.value.length) {
activePathList.value.splice(index, 1)
}
})
loading.value = false
if (!msg) return
ElMessage({ message: msg, type: 'success', duration: 5000 })
}
})
.catch(e => {
loading.value = false
})
}
}
//新建文件夹
const submitDeviceDir = () => {
@@ -526,11 +612,21 @@ const changeType = ref<any>('')
//下载文件
const fileRef = ref()
const handleDownLoad = async (row: any) => {
;(await nDid.value) && fileRef.value && fileRef.value.open(row, nDid.value)
// fileName.value = row?.prjDataPath.split('/')[row?.prjDataPath.split('/').length - 1]
// localStorage.setItem('fileName', fileName.value)
changeType.value = 'download'
localStorage.setItem('changeType', changeType.value)
if (devConType.value == 'CLD') {
ElMessage.info('下载中,请稍等...')
downloadFileFromFrontr({
devId: devId.value,
filePath: row.prjDataPath
}).then(res => {
downLoadFile(row.name, row.name, res)
})
} else {
;(await nDid.value) && fileRef.value && fileRef.value.open(row, nDid.value)
// fileName.value = row?.prjDataPath.split('/')[row?.prjDataPath.split('/').length - 1]
// localStorage.setItem('fileName', fileName.value)
changeType.value = 'download'
localStorage.setItem('changeType', changeType.value)
}
}
//上传文件
const fileName = ref<any>('')

View File

@@ -118,12 +118,15 @@ const open = (text: string, List: any, data?: anyObj, id?: string) => {
}
}
const submit = async () => {
if (form.topoIds == '') {
return ElMessage.warning('请选择拓扑图!')
}
formRef.value.validate(async valid => {
if (valid) {
if (form.id) {
await updateProjects({ ...form, topoIds: form.topoIds == '' ? [] : [form.topoIds] })
await updateProjects({ ...form, topoIds: [form.topoIds] })
} else {
await addProject({ ...form, topoIds: form.topoIds == '' ? [] : [form.topoIds] })
await addProject({ ...form, topoIds: [form.topoIds] })
}
ElMessage.success('保存成功')
tableStore.index()

View File

@@ -43,7 +43,7 @@
:preview-teleported="true"
v-if="row.topologyInfo"
:preview-src-list="[row.topologyImageUrl]"
:src="getUrl(row) ? row.topologyImageUrl : ''"
:src="row.topologyImageUrl"
></el-image>
<span v-else>/</span>
</template>
@@ -199,6 +199,11 @@ const setTableRow = () => {
let list = tableStore.table.data.filter((item: any) => item.engineeringId == engineeringId.value)
tableRef.value.getRef().setCurrentRow(list[0] ?? {})
itemList.value = list?.[0]?.projectInfoList ?? []
if (itemList.value.length > 0) {
itemList.value.forEach((item: any) => {
item.topologyImageUrl = getUrl(item)
})
}
}
// 修改模版
const itemModification = (row: any) => {
@@ -223,6 +228,11 @@ const add = () => {
const currentChange = (data: any) => {
engineeringId.value = data.row.engineeringId
itemList.value = data.row.projectInfoList
if (itemList.value.length > 0) {
itemList.value.forEach((item: any) => {
item.topologyImageUrl = getUrl(item)
})
}
}
// 保存模版
const save = () => {
@@ -238,14 +248,11 @@ const save = () => {
const imgList = ref([])
// 获取拓扑图
const getUrl = async (row: any) => {
if (!row.topologyInfo || row.topologyInfo === '/') return false
try {
const res = await getFileUrl({ filePath: row.topologyInfo })
row.topologyImageUrl = res.data
return true
} catch (error) {
return false
}
if (!row.topologyInfo || row.topologyInfo === '/') return ''
const res = await getFileUrl({ filePath: row.topologyInfo })
row.topologyImageUrl = res.data
return res.data
}
onMounted(() => {

View File

@@ -151,7 +151,7 @@
<el-form-item label="设备型号:" prop="devModel" class="top">
<el-select v-model.trim="form.devModel" filterable placeholder="请选择" clearable>
<el-option
v-for="item in formDevModelOptionsFilter "
v-for="item in formDevModelOptionsFilter"
:key="item.value"
:label="item.label"
:value="item.value"
@@ -164,6 +164,15 @@
<el-option label="CLD" value="CLD"></el-option>
</el-select>
</el-form-item>
<el-form-item label="关联项目:" class="top">
<el-cascader
v-model.trim="form.association"
filterable
:options="engineeringList"
:props="props"
clearable
/>
</el-form-item>
<el-form-item label="排序:" class="top" prop="sort">
<el-input maxlength="32" show-word-limit-number v-model.trim="form.sort" :min="0" />
</el-form-item>
@@ -198,7 +207,7 @@ import TableHeader from '@/components/table/header/index.vue'
import { queryByCode, queryByid, queryCsDictTree } from '@/api/system-boot/dictTree'
import { ElMessage, ElMessageBox } from 'element-plus'
import { activateUser, deluser, passwordConfirm } from '@/api/user-boot/user'
import { downLoadFile } from '@/api/cs-system-boot/manage.ts'
import { downLoadFile } from '@/api/cs-system-boot/manage'
import {
addEquipmentDelivery,
deleteEquipmentDelivery,
@@ -208,7 +217,8 @@ import {
governDeviceRegister,
portableDeviceRegister,
portableDeviceAccess,
getExcelTemplate
getExcelTemplate,
engineeringProject
} from '@/api/cs-system-boot/device'
import html2canvas from 'html2canvas'
import { fullUrl } from '@/utils/common'
@@ -221,17 +231,27 @@ const showQrCode = ref(false)
const devTypeOptions: any = ref([])
const devTypeOptions2: any = ref([])
const devModelOptions2: any = ref([])
const engineeringList: any = ref([])
const deivce: any = ref({})
const ruleFormRef = ref()
const form = reactive({
const form: any = reactive({
cntractNo: '',
devAccessMethod: 'MQTT',
devModel: '',
devType: '',
name: '',
ndid: '',
associatedEngineering: '',
associatedProject: '',
association: [],
sort: 0
})
const props = {
label: 'projectName',
value: 'projectId',
children: 'projectInfoList'
}
const rules = reactive({
name: [{ required: true, message: '请输入设备名', trigger: 'blur' }],
ndid: [{ required: true, message: '请输入网络设备id', trigger: 'blur' }],
@@ -248,19 +268,21 @@ const dialogTitle = ref('新增设备')
const loading = ref<boolean>(false)
const devModelOptions: any = ref([])
const queryTheDictionary = () => {
queryByCode('DEV_CLD').then(res => {
queryByCode('DEV_CLD')
.then(res => {
devTypeOptions2.value = res.data
return queryCsDictTree(res.data.id).then(res => {
devModelOptions2.value = res.data.map((item: any) => {
return {
value: item.id,
label: item.name,
...item
}
})
return {
value: item.id,
label: item.name,
...item
}
})
})
}).then(() => {
queryByCode('Device_Type').then(async res => {
})
.then(() => {
queryByCode('Device_Type').then(async res => {
const id = res.data.id
await queryCsDictTree(id).then(res => {
devTypeOptions.value = res.data.map((item: any) => {
@@ -270,7 +292,7 @@ const queryTheDictionary = () => {
...item
}
})
// let index = devTypeOptions.value.findIndex((item: any) => {
// return item.name == '网关'
// })
@@ -292,10 +314,10 @@ const queryTheDictionary = () => {
})
await tableStore.index()
})
}).catch(error => {
})
.catch(error => {
console.error('查询过程中出现错误:', error)
})
}
const devModelOptionsFilter = computed(() => {
return devModelOptions.value.filter((item: any) => {
@@ -308,7 +330,7 @@ const devModelOptionsFilter = computed(() => {
})
const formDevModelOptionsFilter = computed(() => {
if(form.devAccessMethod === 'CLD'){
if (form.devAccessMethod === 'CLD') {
return devModelOptions2.value.filter((item: any) => {
if (form.devType) {
return item.pid == form.devType
@@ -316,18 +338,17 @@ const formDevModelOptionsFilter = computed(() => {
return true
}
})
}else{
} else {
return devModelOptions.value.filter((item: any) => {
if (form.devType) {
return item.pid == form.devType
} else {
return true
}
})
if (form.devType) {
return item.pid == form.devType
} else {
return true
}
})
}
})
const formDevTypeOptions = computed(() => {
// 如果协议是CLD使用devTypeOptions2否则使用devTypeOptions
if (form.devAccessMethod === 'CLD') {
@@ -362,13 +383,13 @@ const tableStore = new TableStore({
field: 'devType',
formatter: row => {
if (row.row.devAccessMethod === 'CLD') {
// 遍历devTypeOptions2查找匹配
// 遍历devTypeOptions2查找匹配
return devTypeOptions2.value.name
}
}
// 如果是MQTT协议使用devTypeOptions查找
else if (row.row.devAccessMethod === 'MQTT') {
const item = devTypeOptions.value.find((item: any) => item.value == row.cellValue);
return item ? item.label : '/';
const item = devTypeOptions.value.find((item: any) => item.value == row.cellValue)
return item ? item.label : '/'
}
},
minWidth: 120
@@ -378,8 +399,8 @@ const tableStore = new TableStore({
field: 'devModel',
formatter: row => {
const options = row.row.devAccessMethod === 'MQTT' ? devModelOptions.value : devModelOptions2.value
const item = options.find((item: any) => item.value == row.cellValue);
return item ? item.label : '/';
const item = options.find((item: any) => item.value == row.cellValue)
return item ? item.label : '/'
},
minWidth: 120
},
@@ -488,7 +509,8 @@ const tableStore = new TableStore({
minWidth: 80
},
{
title: '操作', fixed: 'right',
title: '操作',
fixed: 'right',
align: 'center',
width: 220,
render: 'buttons',
@@ -677,7 +699,6 @@ const tableStore = new TableStore({
useCORS: true
}).then(canvas => {
let url = canvas.toDataURL('image/png')
console.log('🚀 ~ html2canvas ~ url:', url)
// 下载图片
let a = document.createElement('a')
let event = new MouseEvent('click')
@@ -701,6 +722,10 @@ const tableStore = new TableStore({
for (let key in form) {
form[key] = row[key]
}
form.association = row.associatedProject
? [row.associatedEngineering, row.associatedProject]
: []
form.id = row.id
}
},
@@ -741,7 +766,6 @@ const tableStore = new TableStore({
: ''
}
})
console.log('🚀 ~ loadCallback ~ tableStore.table:', tableStore.table)
tableKey.value += 1
}
})
@@ -877,6 +901,9 @@ const add = () => {
const onSubmit = () => {
ruleFormRef.value.validate((valid: any) => {
if (valid) {
form.associatedEngineering = form.association ? form.association[0] : ''
form.associatedProject = form.association ? form.association[1] : ''
if (dialogTitle.value == '新增设备') {
addEquipmentDelivery(form).then(res => {
ElMessage.success('新增成功')
@@ -923,6 +950,9 @@ const resetForm = () => {
devModel: '',
devType: '',
name: '',
associatedEngineering: '',
associatedProject: '',
association: [],
ndid: ''
}
Object.assign(form, user)
@@ -939,6 +969,15 @@ provide('tableStore', tableStore)
onMounted(() => {
queryTheDictionary()
engineeringProject().then(res => {
engineeringList.value = res.data.filter(item => {
item.projectName = item.engineeringName
item.projectId = item.engineeringId
item.disabled = item.projectInfoList ? false : true
return item
})
})
setTimeout(() => {}, 100)
})

View File

@@ -1,349 +1,326 @@
// 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
) {
// luckysheetff(样式), 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
}
// 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) {
// luckysheetff(样式), 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) {
const borderItem = borders[bor]
// 同时判断边框对象 和 color 属性都存在
if (!borderItem || !borderItem.color) {
continue
}
if (borderItem.color.indexOf('rgb') === -1) {
border[luckyExcel.type[bor]] = {
style: luckyExcel.style[borderItem.style],
color: { argb: borderItem.color.replace('#', '') }
}
} else {
border[luckyExcel.type[bor]] = {
style: luckyExcel.style[borderItem.style],
color: { argb: borderItem.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 }