excel 预览集成

This commit is contained in:
cwchen 2025-11-12 18:11:21 +08:00
parent f608409698
commit 9c4c2f1f28
5 changed files with 438 additions and 5 deletions

View File

@ -26,6 +26,7 @@
"dependencies": {
"@riophae/vue-treeselect": "0.4.0",
"@vue-office/docx": "^1.6.3",
"@vue-office/excel": "^1.7.14",
"@vue/composition-api": "^1.7.2",
"axios": "0.28.1",
"clipboard": "2.0.8",
@ -40,8 +41,11 @@
"js-beautify": "1.13.0",
"js-cookie": "3.0.1",
"jsencrypt": "3.0.0-rc.1",
"jquery": "^3.6.0",
"jquery-mousewheel": "^3.1.13",
"jszip": "^3.10.1",
"lodash": "^4.17.21",
"luckysheet": "^2.1.13",
"mammoth": "^1.11.0",
"nprogress": "0.2.0",
"pdfjs-dist": "^2.16.105",
@ -58,7 +62,8 @@
"vue-pdf": "^4.3.0",
"vue-router": "3.4.9",
"vuedraggable": "2.24.3",
"vuex": "3.6.0"
"vuex": "3.6.0",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@vue/cli-plugin-babel": "4.4.6",

View File

@ -2,6 +2,10 @@ import Vue from 'vue'
import Cookies from 'js-cookie'
// 全局引入 jQueryLuckysheet 需要它
import $ from 'jquery'
window.$ = window.jQuery = $
import Element from 'element-ui'
import './assets/styles/element-variables.scss'

View File

@ -1,13 +1,399 @@
<template>
<div>Excel文档查看</div>
<div class="document-excel">
<div class="viewer-container">
<div id="luckysheet" class="excel-wrapper"></div>
<div v-if="loading" class="overlay state-panel">
<i class="el-icon-loading state-icon"></i>
<p>正在加载 Excel 文档请稍候...</p>
</div>
<div v-else-if="error" class="overlay state-panel">
<i class="el-icon-warning-outline state-icon"></i>
<p>{{ error }}</p>
<el-button type="primary" @click="reload">重新加载</el-button>
</div>
<div v-else-if="!excelUrl" class="overlay state-panel">
<i class="el-icon-document state-icon"></i>
<p>暂未指定 Excel 文件请通过路由参数 url 传入文件地址</p>
</div>
</div>
</div>
</template>
<script>
export default {
import 'jquery-mousewheel'
import LuckySheet from 'luckysheet'
import * as XLSX from 'xlsx'
import 'luckysheet/dist/plugins/css/pluginsCss.css'
import 'luckysheet/dist/plugins/plugins.css'
import 'luckysheet/dist/css/luckysheet.css'
import 'luckysheet/dist/assets/iconfont/iconfont.css'
const DEFAULT_EXCEL_URL = 'http://192.168.0.14:9090/smart-bid/technicalSolutionDatabase/2025/11/12/928206a2fdc74c349781f441d9c010f8.xlsx'
export default {
name: 'DocumentExcel',
data() {
return {
loading: false,
error: null,
excelUrl: null,
workbook: null,
luckySheetInstance: null
}
},
computed: {
routeExcelUrl() {
return this.$route.query.url || this.$route.params.url;
}
},
watch: {
routeExcelUrl: {
immediate: true,
handler(newUrl) {
if (newUrl) {
this.excelUrl = newUrl;
this.loadExcel();
} else {
// URL使URL
this.excelUrl = DEFAULT_EXCEL_URL;
this.loadExcel();
}
}
}
},
mounted() {
//
},
beforeUnmount() {
// LuckySheet
this.destroyLuckySheet();
},
methods: {
// Excel
async loadExcel() {
if (!this.excelUrl) {
this.error = 'Excel 文件地址为空';
return;
}
this.loading = true;
this.error = null;
try {
// Excel
const response = await fetch(this.excelUrl);
if (!response.ok) {
throw new Error(`文件加载失败: ${response.status} ${response.statusText}`);
}
// ArrayBuffer
const arrayBuffer = await response.arrayBuffer();
// 使 XLSX Excel
const workbook = XLSX.read(arrayBuffer, { type: 'array' });
this.workbook = workbook;
// LuckySheet
const luckySheetData = this.convertToLuckySheet(workbook);
// LuckySheet
this.renderLuckySheet(luckySheetData);
} catch (err) {
console.error('加载 Excel 文件失败:', err);
this.error = `加载失败: ${err.message}`;
} finally {
this.loading = false;
}
},
// XLSX 簿 LuckySheet
convertToLuckySheet(workbook) {
if (!workbook || !workbook.SheetNames || workbook.SheetNames.length === 0) {
throw new Error('Excel 文件格式无效或没有工作表');
}
const sheets = [];
workbook.SheetNames.forEach((sheetName, index) => {
const worksheet = workbook.Sheets[sheetName];
if (!worksheet) {
return;
}
//
let sheetData = [];
try {
sheetData = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: '' });
} catch (error) {
console.error(`读取工作表 ${sheetName} 失败:`, error);
sheetData = [];
}
if (!Array.isArray(sheetData)) {
sheetData = [];
}
//
const ref = worksheet['!ref'] ? XLSX.utils.decode_range(worksheet['!ref']) : null;
const rowCount = ref ? ref.e.r + 1 : Math.max(sheetData.length, 36);
const colCount = ref ? ref.e.c + 1 : Math.max(sheetData[0]?.length || 0, 26);
//
const celldata = [];
let maxRow = 0;
let maxCol = 0;
sheetData.forEach((row, rowIndex) => {
if (row && Array.isArray(row)) {
maxRow = Math.max(maxRow, rowIndex);
row.forEach((cell, colIndex) => {
if (cell !== null && cell !== undefined && cell !== '') {
maxCol = Math.max(maxCol, colIndex);
const cellType = typeof cell === 'number' ? 'n' : 'g';
celldata.push({
r: rowIndex,
c: colIndex,
v: {
v: cell,
ct: { fa: 'General', t: cellType },
m: String(cell)
}
});
}
});
}
});
//
const mergeConfig = {};
const merges = worksheet['!merges'] || [];
if (Array.isArray(merges)) {
merges.forEach(merge => {
if (merge?.s && merge?.e) {
const r = merge.s.r;
const c = merge.s.c;
const rs = merge.e.r - merge.s.r + 1;
const cs = merge.e.c - merge.s.c + 1;
if (typeof r === 'number' && typeof c === 'number' &&
typeof rs === 'number' && typeof cs === 'number' &&
rs > 0 && cs > 0) {
mergeConfig[`${r}_${c}`] = { r, c, rs, cs };
}
}
});
}
// LuckySheet
const sheetConfig = {
name: sheetName,
index: index === 0 ? '0' : String(Math.random()),
status: index === 0 ? 1 : 0,
order: index === 0 ? 0 : 1,
row: Math.max(maxRow + 1, 36),
column: Math.max(maxCol + 1, 26),
celldata: celldata,
config: {
merge: mergeConfig
}
};
sheets.push(sheetConfig);
});
if (sheets.length === 0) {
throw new Error('Excel 文件中没有有效数据');
}
return sheets;
},
// LuckySheet
renderLuckySheet(sheetData) {
// loading DOM
this.$nextTick(() => {
//
setTimeout(() => {
try {
const container = document.getElementById('luckysheet');
if (!container) {
throw new Error('容器元素不存在');
}
//
if (container.offsetWidth === 0 || container.offsetHeight === 0) {
setTimeout(() => this.renderLuckySheet(sheetData), 100);
return;
}
//
container.innerHTML = '';
// LuckySheet
if (this.luckySheetInstance) {
try {
LuckySheet.destroy();
} catch (e) {
console.warn('销毁旧实例失败:', e);
}
}
// LuckySheet -
this.luckySheetInstance = LuckySheet.create({
container: 'luckysheet',
data: sheetData,
allowEdit: false,
showtoolbar: false,
showsheetbar: sheetData.length > 1,
showstatisticBar: false,
enableAddRow: false,
enableAddCol: false
});
console.log('LuckySheet 初始化成功');
} catch (err) {
console.error('LuckySheet 渲染失败:', err);
this.error = `表格渲染失败: ${err.message}`;
}
}, 200);
});
},
//
reload() {
this.loadExcel();
},
// LuckySheet
destroyLuckySheet() {
try {
LuckySheet.destroy();
this.luckySheetInstance = null;
} catch (err) {
console.warn('销毁 LuckySheet 失败:', err);
}
},
// Excel
exportExcel() {
if (!this.luckySheetInstance) {
this.$message.warning('没有可导出的数据');
return;
}
try {
// LuckySheet
const luckysheetData = LuckySheet.getAllSheets();
// 簿
const workbook = XLSX.utils.book_new();
//
luckysheetData.forEach((sheet) => {
//
const maxRow = Math.max(...sheet.celldata.map(cell => cell.r)) + 1;
const maxCol = Math.max(...sheet.celldata.map(cell => cell.c)) + 1;
const data = [];
for (let r = 0; r < maxRow; r++) {
const row = [];
for (let c = 0; c < maxCol; c++) {
const cell = sheet.celldata.find(item => item.r === r && item.c === c);
row.push(cell ? cell.v : '');
}
data.push(row);
}
//
const worksheet = XLSX.utils.aoa_to_sheet(data);
// 簿
XLSX.utils.book_append_sheet(workbook, worksheet, sheet.name);
});
//
XLSX.writeFile(workbook, 'exported-excel.xlsx');
this.$message.success('导出成功');
} catch (err) {
console.error('导出失败:', err);
this.$message.error('导出失败');
}
}
}
}
</script>
<style>
<style scoped>
.document-excel {
height: 100vh;
background: #f5f5f5;
}
.viewer-container {
position: relative;
height: 100%;
width: 100%;
}
.overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.9);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 1000;
}
.state-panel {
text-align: center;
padding: 20px;
}
.state-icon {
font-size: 48px;
color: #409EFF;
margin-bottom: 16px;
}
.state-panel p {
margin: 16px 0;
color: #606266;
font-size: 14px;
}
.excel-wrapper {
height: 100%;
width: 100%;
background: white;
}
/* 确保 LuckySheet 样式正确应用 */
:deep(#luckysheet) {
height: 100% !important;
width: 100% !important;
}
/* 响应式设计 */
@media (max-width: 768px) {
.document-excel {
height: calc(100vh - 60px);
}
.state-icon {
font-size: 36px;
}
.state-panel p {
font-size: 12px;
}
}
</style>

View File

@ -19,7 +19,7 @@
//
const defaultParams = {
fileType: 'technical_solution',
uploadType: 'pdf、doc、docx',
uploadType: 'pdf、doc、docx、xls、xlsx',
maxFileTips: '500MB',
fileUploadRule: {
fileUploadType: 'technical_solution',

View File

@ -107,6 +107,44 @@ module.exports = {
config.plugins.delete('preload') // TODO: need test
config.plugins.delete('prefetch') // TODO: need test
// 处理 .ico 文件 - 必须在 CSS 规则之前
config.module
.rule('ico')
.test(/\.ico$/)
.use('file-loader')
.loader('file-loader')
.options({
name: 'static/[name].[hash:8].[ext]',
esModule: false
})
.end()
// 配置 CSS loader 忽略 .ico 文件的 url 处理
const cssRule = config.module.rule('css')
if (cssRule && cssRule.oneOfs) {
cssRule.oneOfs.store.forEach((oneOf) => {
oneOf.uses.store.forEach((use, useKey) => {
if (use.name && use.name.includes('css-loader')) {
oneOf.use(useKey).tap(options => {
if (!options) options = {}
const originalUrl = options.url
options.url = (url, resourcePath) => {
// 忽略 .ico 文件的 url避免 webpack 处理
if (url && typeof url === 'string' && (url.endsWith('.ico') || url.includes('.ico'))) {
return false
}
if (typeof originalUrl === 'function') {
return originalUrl(url, resourcePath)
}
return originalUrl !== false
}
return options
})
}
})
})
}
// set svg-sprite-loader
config.module
.rule('svg')