vue3上傳excel并在線預(yù)覽的實(shí)現(xiàn)
前言
關(guān)于實(shí)現(xiàn)excel文檔在線預(yù)覽的做法,一種方式是通過講文檔里的數(shù)據(jù)處理成html,一種是將文檔處理成圖片進(jìn)行預(yù)覽,這里使用的是第一種。
安裝 xlsx 依賴
npm i xlsx --save
XLSX.utils.sheet_to_html
使用XLSX.utils.sheet_to_html方法將工作表(workSheet)轉(zhuǎn)化成html表格的字符串表示,然后顯示在前端頁面,按照表格的行列結(jié)構(gòu)進(jìn)行排序,從而實(shí)現(xiàn)在線預(yù)覽的效果
import * as XLSX from 'xlsx'
export const file2Preview = (file: File) => {
return new Promise(function (resolve) {
const reader = new FileReader();// 文件加載事件
reader.onload = function (e) {
const data = e.target?.result;
const workbook = XLSX.read(data, {
type: "binary", cellDates: true,
});
// 拿第-個(gè)sheet
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
const html = XLSX.utils.sheet_to_html(worksheet);
// 返回html
resolve(html);
};
reader.readAsBinaryString(file);
});
};調(diào)用實(shí)現(xiàn)
<template>
<n-upload
v-model:file-list="fileList"
action="https://www.mocky.io/v2/5e4bafc63100007100d8b70f"
@change="handleUploadChange"
@remove="handleRemove"
@update:file-list="handleFileListChange"
>
<n-button>上傳文件</n-button>
</n-upload>
<div class="flex-center preview-table" id="previewTable"></div>
</template>
<script lang="ts" setup>
import { defineComponent, ref } from 'vue'
import { useMessage } from 'naive-ui'
import type { UploadFileInfo } from 'naive-ui'
import { NButton } from "naive-ui";
import {file2Preview} from '@main/utils/index';
const message = useMessage()
const fileListRef = ref<UploadFileInfo[]>([
])
const fileList = ref(fileListRef)
const handleUploadChange = async (data: { fileList: UploadFileInfo[] }) => {
const html= await file2Preview(data.fileList[0].file as File);
const previewTable = document.getElementById('previewTable');
}
const handleRemove = (data: { file: UploadFileInfo, fileList: UploadFileInfo[] }) => {
if (data.file.id === 'text-message') {
message.info('居然沒傳上去,算了,刪了吧')
}
else if (data.file.id === 'notification') {
message.error('不行,這個(gè)有用,不許刪')
return false
}
else if (data.file.id === 'contact') {
message.loading('不知道這個(gè)有沒有用,等我問問服務(wù)器能不能刪', {
duration: 4000
})
return new Promise((resolve) => {
setTimeout(() => {
message.error('不行,他們也不許刪這個(gè)')
resolve(false)
}, 4000)
})
}
}
const handleFileListChange = () => {
message.info('是的,file-list 的值變了')
}
</script>
<style lang="less" scoped>
::v-deep table {
border: 1px solid #000 !important;
margin-top: 10px;
border-collapse: collapse;
}
::v-deep th {
border: 1px solid #000 !important;
}
::v-deep tr {
border: 1px solid #000 !important;
}
::v-deep td {
border: 1px solid #000 !important;
text-align: center;
min-width:20px;
height: 20px;
line-height: 20px;
padding: 4px;
color:#3e3e3e;
}
</style>
XLSX.utils.sheet_to_json
XLSX.utils.sheet_to_json用于將excel表格中的工作表(sheet)轉(zhuǎn)換成JSON格式的函數(shù),使用組件顯示
export const file2Data = (file: File) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = function (e) {
const data = e.target?.result;
if (!data) {
reject(new Error("Failed to read file data"));
return;
}
try {
const workbook = XLSX.read(data, { type: "binary" });
const result: any[] = [];
workbook.SheetNames.forEach((sheetName) => {
const sheet = workbook.Sheets[sheetName];
const jsonData = XLSX.utils.sheet_to_json(sheet, { header: 1, raw: false });
if (jsonData.length > 0) {
result.push({
sheetName,
sheet: jsonData
});
}
});
console.log(result); // 輸出解析后的數(shù)據(jù)
resolve(result);
} catch (error) {
reject(error);
}
};
reader.onerror = function (e) {
reject(new Error("FileReader error: " + e.target?.error?.message));
};
reader.readAsBinaryString(file);
});
};調(diào)用實(shí)現(xiàn)
<script lang="ts" setup>
import { defineComponent, ref } from 'vue'
import { useMessage } from 'naive-ui'
import type { UploadFileInfo } from 'naive-ui'
import { NButton } from "naive-ui";
import {file2Data} from '@main/utils/index';
const message = useMessage()
const fileListRef = ref<UploadFileInfo[]>([
])
const datas = ref({
source:[],
columns:[]
})
const fileList = ref(fileListRef)
const handleUploadChange = async (data: { fileList: UploadFileInfo[] }) => {
fileListRef.value = data.fileList;
const excelData = await file2Data(data.fileList[0].file as File)
datas.value.source = excelData[0].sheet;
datas.value.columns = [];
Object.keys(datas.value.source[0]).map((v) => {
datas.value.columns = [
...datas.value.columns,
{
title: datas.value.source[0][v],
key: v
}
]
})
datas.value.source = datas.value.source.slice(1);
console.log(datas.value);
}
const handleRemove = (data: { file: UploadFileInfo, fileList: UploadFileInfo[] }) => {
if (data.file.id === 'text-message') {
message.info('居然沒傳上去,算了,刪了吧')
}
else if (data.file.id === 'notification') {
message.error('不行,這個(gè)有用,不許刪')
return false
}
else if (data.file.id === 'contact') {
message.loading('不知道這個(gè)有沒有用,等我問問服務(wù)器能不能刪', {
duration: 4000
})
return new Promise((resolve) => {
setTimeout(() => {
message.error('不行,他們也不許刪這個(gè)')
resolve(false)
}, 4000)
})
}
}
const handleFileListChange = () => {
message.info('是的,file-list 的值變了')
}
</script>
<template>
<n-upload
v-model:file-list="fileList"
action="https://www.mocky.io/v2/5e4bafc63100007100d8b70f"
@change="handleUploadChange"
@remove="handleRemove"
@update:file-list="handleFileListChange"
>
<n-button>上傳文件</n-button>
</n-upload>
<n-data-table
id="previewTable"
class="preview-table"
:columns="datas.columns"
:data="datas.source"
:pagination="false"
:bordered="false"
/>
</template>
<style lang="less" scoped>
::v-deep table {
border: 1px solid #000 !important;
margin-top: 10px;
border-collapse: collapse;
}
::v-deep th {
border: 1px solid #000 !important;
}
::v-deep tr {
border: 1px solid #000 !important;
}
::v-deep td {
border: 1px solid #000 !important;
text-align: center;
min-width:20px;
height: 20px;
line-height: 20px;
padding: 4px;
color:#3e3e3e;
}
</style>
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- vue3采用xlsx庫實(shí)現(xiàn)本地上傳excel文件功能
- Vue3中使用exceljs和file-saver實(shí)現(xiàn)Excel導(dǎo)出(含圖片導(dǎo)出)功能完整方案
- Vue3中Excel導(dǎo)出的性能優(yōu)化與實(shí)戰(zhàn)指南
- vue3+luckysheet實(shí)現(xiàn)在線編輯Excel的項(xiàng)目實(shí)踐
- Vue3使用exceljs將excel文件轉(zhuǎn)化為html預(yù)覽最佳方案
- Vue3使用Univer Docs創(chuàng)建在線編輯Excel的示例代碼
- Vue3項(xiàng)目中通過LuckySheet實(shí)現(xiàn)Excel在線編輯功能
相關(guān)文章
Slots Emit和Props穿透組件封裝實(shí)現(xiàn)摸魚加鐘
這篇文章主要為大家介紹了Slots Emit和Props穿透組件封裝實(shí)現(xiàn)示例詳解,為摸魚加個(gè)鐘,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
elementUI Vue 單個(gè)按鈕顯示和隱藏的變換功能(兩種方法)
小編最近遇到這樣的需求,當(dāng)點(diǎn)擊一個(gè)按鈕可以變換里面字的內(nèi)容,剛開始還真是一頭霧水,不知所措。仔細(xì)想想屢屢思緒,很容易的解決了。接下來通過本文給大家介紹elementUI Vue 單個(gè)按鈕顯示和隱藏的變換功能,需要的朋友可以參考下2018-09-09
vue+vuex+axios實(shí)現(xiàn)登錄、注冊(cè)頁權(quán)限攔截
下面小編就為大家分享一篇vue+vuex+axios實(shí)現(xiàn)登錄、注冊(cè)頁權(quán)限攔截,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03
vue-cli3.X快速創(chuàng)建項(xiàng)目的方法步驟
這篇文章主要介紹了vue-cli3.X快速創(chuàng)建項(xiàng)目的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
vue單頁面SEO優(yōu)化的實(shí)現(xiàn)
本文主要介紹了vue單頁面SEO優(yōu)化的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
關(guān)于vue-property-decorator的基礎(chǔ)使用實(shí)踐
這篇文章主要介紹了關(guān)于vue-property-decorator的基礎(chǔ)使用實(shí)踐,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08

