vue3純前端表格數(shù)據(jù)的導(dǎo)出與導(dǎo)入實(shí)現(xiàn)方式
項(xiàng)目場(chǎng)景:
我期望達(dá)成在純前端環(huán)境下進(jìn)行 excel 表格文件的下載操作,與此同時(shí),對(duì)所下載的表格文件的樣式加以調(diào)整與優(yōu)化,使其呈現(xiàn)出更符合需求的外觀和格式布局,從而滿足特定的展示與使用要求。
表格數(shù)據(jù)導(dǎo)出
1、安裝 xlsx-js-style
提示:這里描述項(xiàng)目中遇到的問(wèn)題:
先安裝庫(kù) xlsx-js-style
npm install xlsx-js-style
2、自定義組件
自定義組件,這里附全部代碼,設(shè)置單元格格式代碼也在其中
<script lang="ts" setup> import { computed, nextTick, ref, watch } from "vue" import * as XLSX from "xlsx-js-style" interface Props { modelValue: boolean downloadList: any columnList: any } const props = withDefaults(defineProps<Props>(), { modelValue: false, downloadList: [], columnList: [] }) const downloadList = computed(() => props.downloadList) const emit = defineEmits<{ (e: "update:modelValue", value: boolean): boolean }>() const columnList = computed(() => props.columnList) //#region 導(dǎo)出 const tableRef = ref<any>(null) // 導(dǎo)出為 Excel const exportToExcel = () => { // 獲取 el-table 的引用 tableRef.value = document.querySelector("#download-table") // 將 el-table 數(shù)據(jù)轉(zhuǎn)換為二維數(shù)組 const dataArray = [] const headers: any = [] tableRef.value.querySelectorAll(".el-table__header-wrapper th").forEach((th: any) => { headers.push(th.textContent.trim()) }) dataArray.push(headers) const rowsToExport = tableRef.value.querySelectorAll(".el-table__body-wrapper tbody tr") console.log(rowsToExport, "rowsToExport") rowsToExport.forEach((row: any) => { const rowData: any = [] row.querySelectorAll("td").forEach((cell: any) => { rowData.push(cell.textContent.trim()) }) dataArray.push(rowData) }) // 創(chuàng)建一個(gè)新的工作簿 const workbook = XLSX.utils.book_new() // 創(chuàng)建一個(gè)新的工作表 const worksheet = XLSX.utils.aoa_to_sheet(dataArray) console.log(dataArray, "dataArray") // 設(shè)置列寬 const columnWidth = 20 // 列寬為20個(gè)字符 const numColumns = dataArray[0].length // 獲取列數(shù) worksheet["!cols"] = Array(numColumns).fill({ wch: columnWidth }) // // 設(shè)置列高 const rowHeight = 105 // 行高為110像素 const numRows = dataArray.length // 獲取行數(shù) worksheet["!rows"] = Array(numRows).fill({ hpx: rowHeight }) worksheet["!rows"][0] = { hpx: 15 } // 單獨(dú)設(shè)置第一行的行高 // 設(shè)置單元格樣式 const cellStyle = { font: { name: "微軟黑體", // 字體名稱 sz: 13, // 字體大小 color: { rgb: "000000" }, // 字體顏色 bold: false // 字體不加粗 }, border: { top: { style: "thin", color: { rgb: "000000" } }, bottom: { style: "thin", color: { rgb: "000000" } }, left: { style: "thin", color: { rgb: "000000" } }, right: { style: "thin", color: { rgb: "000000" } } }, alignment: { horizontal: "center", vertical: "center", wrapText: true // 設(shè)置文字自動(dòng)換行 } } // 遍歷數(shù)據(jù)數(shù)組,為每個(gè)單元格應(yīng)用樣式 dataArray.forEach((row, rowIndex) => { row.forEach((cell: any, columnIndex: any) => { const cellAddress = XLSX.utils.encode_cell({ c: columnIndex, r: rowIndex }) worksheet[cellAddress].s = cellStyle }) }) // 表頭顏色加粗 if (dataArray[0]) { dataArray[0].forEach((cell: any, columnIndex: any) => { const cellAddress = XLSX.utils.encode_cell({ c: columnIndex, r: 0 }) worksheet[cellAddress].s = { ...cellStyle, font: { ...cellStyle.font, bold: true } } // 確保表頭字體加粗 }) } // 將工作表添加到工作簿 XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1") // 將工作簿保存為 Excel 文件 const timestamp = new Date().getTime() const fileName = `寶貝統(tǒng)計(jì)_${timestamp}.xlsx` XLSX.writeFile(workbook, fileName) emit("update:modelValue", false) } //#endregion watch( () => props.modelValue, (value: any) => { if (value) { console.log(downloadList.value) nextTick(() => { exportToExcel() }) } } ) </script> <template> <el-table style="display: none" :data="downloadList" id="download-table"> <el-table-column v-for="(item, index) in columnList" :key="index" :prop="item.prop" :label="item.label" align="center" /> </el-table> </template> <style lang="scss" scoped></style>
3、使用
使用是時(shí)候是相當(dāng)于在頁(yè)面上設(shè)置個(gè)不可間=見(jiàn)的表格進(jìn)行下載 將需要下載的數(shù)據(jù)傳入即可,可以進(jìn)行改進(jìn),表單項(xiàng)也傳入,這樣就可以隨意下載任何數(shù)據(jù)了
import DownloadExcel from "@/components/DownloadExcel/index.vue" const columnList = [ { prop: "index", label: "序號(hào)" }, { prop: "username", label: "用戶名" }, { prop: "roles", label: "角色" }, { prop: "phone", label: "手機(jī)號(hào)" }, { prop: "email", label: "郵箱" }, { prop: "status", label: "狀態(tài)" }, { prop: "createTime", label: "創(chuàng)建時(shí)間" } ] const downloadList = ref<any[]>([]) const isDownload = ref<boolean>(false) const exportToExcel = () => { if (multipleSelection.value.length == 0) { ElMessage.error("請(qǐng)選擇要下載的寶貝") return } downloadList.value = multipleSelection.value.map((item: any, index: number) => { return { index: index, // 序號(hào) username: item.username, // 用戶名 roles: item.roles, // 角色 phone: item.phone, // 手機(jī)號(hào) email: item.email, // 郵箱 status: item.status ? "啟用" : "禁用", // 狀態(tài) createTime: item.createTime // 創(chuàng)建時(shí)間 } }) isDownload.value = true }
<download-excel v-model="isDownload" :downloadList="downloadList" :columnList="columnList" /> <div> <el-tooltip content="下載"> <el-button type="primary" :icon="Download" circle @click="exportToExcel" /> </el-tooltip> </div>
表格數(shù)據(jù)導(dǎo)入
1、安裝 xlsx
npm install xlsx --save
2、引入
import * as XLSX from "xlsx"
3、使用
<el-upload class="upload-demo" ref="upload" action="" :auto-upload="false" accept="" :on-change="analysisExcel" multiple :show-file-list="false" > <el-button type="primary" :icon="Link">導(dǎo)入文件列表</el-button> </el-upload>
import * as XLSX from "xlsx" const loading = ref<boolean>(false) const tableData = ref<any[]>([]) const analysisExcel = (file: any) => { loading.value = true console.log(file) // 只能上傳一個(gè)Excel,重復(fù)上傳會(huì)覆蓋之前的 file = file.raw const reader = new FileReader() reader.readAsArrayBuffer(file) reader.onload = function () { const buffer: any = reader.result const bytes = new Uint8Array(buffer) const length = bytes.byteLength let binary = "" for (let i = 0; i < length; i++) { binary += String.fromCharCode(bytes[i]) } const wb = XLSX.read(binary, { type: "binary" }) const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]) console.log(outdata) let da = [...outdata] // 這里是把表格里面的名稱改成表格里面的字段 da = da.map((item: any) => { const newItem = { index: Number(item["序號(hào)"]), // 序號(hào) username: item["用戶名"], // 用戶名 roles: item["角色"], // 角色 phone: item["手機(jī)號(hào)"], // 手機(jī)號(hào) email: item["郵箱"], // 郵箱 status: item["狀態(tài)"], // 狀態(tài) createTime: item["創(chuàng)建時(shí)間"] // 創(chuàng)建時(shí)間 } return newItem }) console.log(da) tableData.value = da loading.value = false } }
總結(jié)
到此這篇關(guān)于vue3純前端表格數(shù)據(jù)的導(dǎo)出與導(dǎo)入實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)vue3表格數(shù)據(jù)導(dǎo)出與導(dǎo)入內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
前端vue-cli項(xiàng)目中使用img圖片和background背景圖的幾種方法
這篇文章主要介紹了前端vue-cli項(xiàng)目中使用img圖片和background背景圖的幾種方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11Vue3.x+Element Plus仿制Acro Design簡(jiǎn)潔模式實(shí)現(xiàn)分頁(yè)器組件
開(kāi)發(fā)中難免會(huì)遇到寬度很窄的列表需要使用分頁(yè)器的情況。本文將利用Vue3.x+Element Plus仿制Acro Design簡(jiǎn)潔模式實(shí)現(xiàn)分頁(yè)器組件,感興趣的可以了解一下2023-02-02vue-resourc發(fā)起異步請(qǐng)求的方法
這篇文章主要介紹了vue-resourc發(fā)起異步請(qǐng)求的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02vue項(xiàng)目實(shí)現(xiàn)頁(yè)面跳轉(zhuǎn)的方法
這篇文章主要給大家分享的是vue項(xiàng)目實(shí)現(xiàn)頁(yè)面跳轉(zhuǎn)的方法,vue-router是前端開(kāi)發(fā)中用來(lái)實(shí)現(xiàn)路由頁(yè)面跳轉(zhuǎn)的一個(gè)模塊。下面小編將帶來(lái)如何在已經(jīng)創(chuàng)建好的vue-router項(xiàng)目基礎(chǔ)下實(shí)現(xiàn)頁(yè)面跳轉(zhuǎn),需要的朋友可以參考一下2021-11-11簡(jiǎn)易vuex4核心原理及實(shí)現(xiàn)源碼分析
這篇文章主要為大家介紹了簡(jiǎn)易vuex4核心原理及實(shí)現(xiàn)源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01Vant的Tabbar標(biāo)簽欄引入自定義圖標(biāo)方式
這篇文章主要介紹了Vant的Tabbar標(biāo)簽欄引入自定義圖標(biāo)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04