<template> <div> <button @click="previewFile">Preview Excel</button> <iframe ref="previewIframe" v-if="showPreview" :src="previewUrl" width="100%" height="500"></iframe> </div> </template> <script> import XLSX from 'xlsx'; export default { data() { return { showPreview: false, previewUrl: '', }; }, methods: { async previewFile() { try { // 获取文件内容 const fileContent = await this.getFileContent(); // 使用 xlsx 库将 .xlsx 文件转换为 HTML const workbook = XLSX.read(fileContent, { type: 'buffer' }); const sheetName = workbook.SheetNames[0]; const sheet = workbook.Sheets[sheetName]; // 转换为 HTML 表格 const tableHtml = XLSX.utils.sheet_to_html(sheet); // 创建 HTML 文档并嵌入表格 const htmlDoc = ` <!DOCTYPE html> <html> <head> <title>Excel Preview</title> </head> <body> ${tableHtml} </body> </html> `; // 将 HTML 写入 Blob URL const blob = new Blob([htmlDoc], { type: 'text/html' }); const url = URL.createObjectURL(blob); // 更新预览 URL this.previewUrl = url; this.showPreview = true; // 清理工作 this.$refs.previewIframe.onload = () => { setTimeout(() => { URL.revokeObjectURL(url); }, 60000); // 撤销 URL 以避免内存泄漏 }; } catch (error) { console.error('Error while previewing file:', error); } }, async getFileContent() { // 这里应该返回一个 Promise,它解析为文件的 Blob 对象 // 你可以从服务器获取文件,或者让用户上传文件 // 作为示例,我们返回一个空的 Blob 对象 return new Blob(); }, }, }; </script>
博客摘录「 node版本如何升级」2024年1月23日
最新推荐文章于 2024-08-13 11:55:13 发布