SpreadsheetViewer.vue
9.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
<template>
<div class="spreadsheet-viewer">
<!-- 加载状态 -->
<div v-if="loading" class="loading-state">
<i class="fas fa-spinner fa-spin"></i>
<span>加载电子表格中...</span>
</div>
<!-- 错误状态 -->
<div v-else-if="error" class="error-state">
<i class="fas fa-exclamation-triangle"></i>
<p class="error-text">{{ error }}</p>
<div class="error-actions">
<el-button @click="loadSpreadsheet" size="small">重试</el-button>
<el-button type="primary" @click="handleDownload" size="small">
<i class="fas fa-download"></i>
下载文件
</el-button>
</div>
</div>
<!-- Univer 容器 -->
<div v-else class="sheet-container">
<UniverSheet
ref="univerRef"
class="univer-component"
/>
<!-- 自定义下载按钮 (悬浮) -->
<div class="custom-toolbar">
<el-tooltip content="下载 Excel 文件" placement="bottom">
<div class="toolbar-btn" @click="handleDownload">
<i class="fas fa-download"></i>
</div>
</el-tooltip>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from "vue";
import { ElButton, ElMessage, ElTooltip } from "element-plus";
import * as filesApi from "@/api/files";
import UniverSheet from "./UniverSheet.vue";
import { LocaleType } from "@univerjs/core";
import * as XLSX from "xlsx";
import { fileCache } from "@/utils/fileCache";
interface Props {
fileId: string | number;
fileName: string;
isChatAnswer?: boolean;
}
const props = defineProps<Props>();
const univerRef = ref<InstanceType<typeof UniverSheet> | null>(null);
const loading = ref(true);
const error = ref<string | null>(null);
// 下载文件
const handleDownload = async () => {
try {
// 如果是 Codex 文件,尝试从缓存读取
let response;
if (props.isChatAnswer) {
try {
const cached = await fileCache.getFile(props.fileId);
if (cached && cached.content instanceof Blob) {
response = cached.content;
} else {
response = await filesApi.downloadFile(props.fileId);
}
} catch (error) {
response = await filesApi.downloadFile(props.fileId);
}
} else {
response = await filesApi.downloadFile(props.fileId);
}
let blob: Blob;
if (response instanceof Blob) {
blob = response;
} else if (response.data instanceof Blob) {
blob = response.data;
} else if (props.isChatAnswer && response.data?.content) {
blob = new Blob([response.data.content], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
} else {
throw new Error("下载响应格式错误");
}
const fileName = props.fileName || String(props.fileId);
const a = document.createElement("a");
a.href = window.URL.createObjectURL(blob);
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(a.href);
ElMessage.success("文件下载成功");
} catch (e: any) {
ElMessage.error(`文件下载失败: ${e.message}`);
}
};
// 简单的转换逻辑,确保能预览数据
const convertXlsxToUniverData = (workbook: XLSX.WorkBook) => {
const sheets: any = {};
const sheetOrder: string[] = [];
workbook.SheetNames.forEach((sheetName) => {
const worksheet = workbook.Sheets[sheetName];
if (!worksheet) return;
const sheetId = "sheet-" + sheetName.replace(/\s+/g, "_");
sheetOrder.push(sheetId);
const cellData: any = {};
const range = worksheet["!ref"] ? XLSX.utils.decode_range(worksheet["!ref"]) : { s: { r: 0, c: 0 }, e: { r: 10, c: 10 } };
for (let R = range.s.r; R <= range.e.r; ++R) {
const rowData: any = {};
let hasRowData = false;
for (let C = range.s.c; C <= range.e.c; ++C) {
const cellAddress = XLSX.utils.encode_cell({ r: R, c: C });
const cell = worksheet[cellAddress];
if (cell && cell.v !== undefined) {
rowData[C] = {
v: cell.v,
m: cell.w !== undefined ? String(cell.w) : String(cell.v),
};
hasRowData = true;
}
}
if (hasRowData) {
cellData[R] = rowData;
}
}
sheets[sheetId] = {
id: sheetId,
name: sheetName,
cellData,
rowCount: Math.max(range.e.r + 20, 100),
columnCount: Math.max(range.e.c + 10, 20),
};
});
if (sheetOrder.length === 0) {
// 如果没有工作表,创建一个默认的
const defaultId = "sheet-1";
sheetOrder.push(defaultId);
sheets[defaultId] = {
id: defaultId,
name: "Sheet1",
cellData: {},
rowCount: 100,
columnCount: 20,
};
}
const univerData = {
id: "workbook-" + Date.now(),
sheetOrder,
sheets,
appVersion: "3.0.0",
locale: LocaleType.ZH_CN,
};
return univerData;
};
// 加载电子表格
const loadSpreadsheet = async () => {
loading.value = true;
error.value = null;
try {
const fileId = props.fileId;
let blob: Blob | null = null;
// 1. 尝试从持久化缓存读取
try {
const cached = await fileCache.getFile(fileId);
if (cached && cached.content instanceof Blob) {
console.log("电子表格命中持久化缓存:", fileId);
blob = cached.content;
}
} catch (e) {
console.warn("读取电子表格持久化缓存失败:", e);
}
if (!blob) {
// 1. 下载文件
let response;
if (props.isChatAnswer) {
try {
const cached = await fileCache.getFile(props.fileId);
if (cached && cached.content instanceof Blob) {
response = cached.content;
} else {
response = await filesApi.downloadFile(props.fileId);
}
} catch (error) {
response = await filesApi.downloadFile(props.fileId);
}
} else {
response = await filesApi.downloadFile(props.fileId);
}
if (response instanceof Blob) {
blob = response;
} else if (response.data instanceof Blob) {
blob = response.data;
} else if (props.isChatAnswer && response.data?.content) {
blob = new Blob([response.data.content], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
} else {
throw new Error("下载响应格式错误");
}
// 写入持久化缓存
if (blob instanceof Blob) {
await fileCache.setFile({
fileId,
content: blob,
type: "spreadsheet",
fileName: props.fileName,
});
}
}
// 2. 解析数据 (在 loading 关闭前完成解析)
const arrayBuffer = await blob.arrayBuffer();
// 检查是否真的是 Excel 文件格式 (Zip 结构)
const fileName = props.fileName || "";
const fileExt = fileName.split(".").pop()?.toLowerCase() || "";
if (fileExt === 'xls') {
throw new Error("暂不支持预览旧版 .xls 格式。请将其另存为 .xlsx 格式后再上传,或直接下载查看。");
}
const wb = XLSX.read(arrayBuffer, { type: "array" });
const univerData = convertXlsxToUniverData(wb);
// 3. 关闭加载状态,显示 UniverSheet 组件
loading.value = false;
// 4. 等待 DOM 渲染和 UniverSheet 挂载
await nextTick();
if (univerRef.value) {
univerRef.value.createWorkbook(univerData);
ElMessage.success("文件加载成功");
} else {
error.value = "组件初始化失败";
}
} catch (err: any) {
console.error("❌ 加载电子表格失败:", err);
error.value = `加载失败: ${err.message || "未知错误"}`;
loading.value = false;
}
};
// 监听 fileId 变化
watch(
() => props.fileId,
async (newFileId, oldFileId) => {
if (newFileId !== oldFileId) {
await loadSpreadsheet();
}
},
);
onMounted(() => {
loadSpreadsheet();
});
</script>
<style scoped lang="scss">
.spreadsheet-viewer {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
background-color: var(--color-bg);
overflow: hidden;
position: relative;
.loading-state,
.error-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
flex: 1;
gap: 16px;
color: var(--color-text-secondary);
i {
font-size: 48px;
}
span,
.error-text {
font-size: 14px;
margin: 0;
}
}
.error-state {
i {
color: #f56c6c;
}
.error-actions {
display: flex;
gap: 12px;
margin-top: 8px;
}
}
.sheet-container {
width: 100%;
height: 100%;
position: relative;
.univer-component {
width: 100%;
height: 100%;
}
}
.custom-toolbar {
position: absolute;
top: 10px;
right: 20px;
z-index: 100;
display: flex;
gap: 8px;
.toolbar-btn {
width: 32px;
height: 32px;
border-radius: 4px;
background: none;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
color: var(--color-text, #606266);
transition: all 0.2s;
padding: 6px;
border: none;
&:hover {
background: rgba(0, 0, 0, 0.05);
}
}
}
}
</style>