vue3純前端表格數據的導出與導入實現(xiàn)方式
項目場景:
我期望達成在純前端環(huán)境下進行 excel 表格文件的下載操作,與此同時,對所下載的表格文件的樣式加以調整與優(yōu)化,使其呈現(xiàn)出更符合需求的外觀和格式布局,從而滿足特定的展示與使用要求。
表格數據導出

1、安裝 xlsx-js-style
提示:這里描述項目中遇到的問題:
先安裝庫 xlsx-js-style
npm install xlsx-js-style
2、自定義組件
自定義組件,這里附全部代碼,設置單元格格式代碼也在其中
<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 導出
const tableRef = ref<any>(null)
// 導出為 Excel
const exportToExcel = () => {
// 獲取 el-table 的引用
tableRef.value = document.querySelector("#download-table")
// 將 el-table 數據轉換為二維數組
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)建一個新的工作簿
const workbook = XLSX.utils.book_new()
// 創(chuàng)建一個新的工作表
const worksheet = XLSX.utils.aoa_to_sheet(dataArray)
console.log(dataArray, "dataArray")
// 設置列寬
const columnWidth = 20 // 列寬為20個字符
const numColumns = dataArray[0].length // 獲取列數
worksheet["!cols"] = Array(numColumns).fill({ wch: columnWidth })
// // 設置列高
const rowHeight = 105 // 行高為110像素
const numRows = dataArray.length // 獲取行數
worksheet["!rows"] = Array(numRows).fill({ hpx: rowHeight })
worksheet["!rows"][0] = { hpx: 15 } // 單獨設置第一行的行高
// 設置單元格樣式
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 // 設置文字自動換行
}
}
// 遍歷數據數組,為每個單元格應用樣式
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)計_${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、使用
使用是時候是相當于在頁面上設置個不可間=見的表格進行下載 將需要下載的數據傳入即可,可以進行改進,表單項也傳入,這樣就可以隨意下載任何數據了
import DownloadExcel from "@/components/DownloadExcel/index.vue"
const columnList = [
{
prop: "index",
label: "序號"
},
{
prop: "username",
label: "用戶名"
},
{
prop: "roles",
label: "角色"
},
{
prop: "phone",
label: "手機號"
},
{
prop: "email",
label: "郵箱"
},
{
prop: "status",
label: "狀態(tài)"
},
{
prop: "createTime",
label: "創(chuàng)建時間"
}
]
const downloadList = ref<any[]>([])
const isDownload = ref<boolean>(false)
const exportToExcel = () => {
if (multipleSelection.value.length == 0) {
ElMessage.error("請選擇要下載的寶貝")
return
}
downloadList.value = multipleSelection.value.map((item: any, index: number) => {
return {
index: index, // 序號
username: item.username, // 用戶名
roles: item.roles, // 角色
phone: item.phone, // 手機號
email: item.email, // 郵箱
status: item.status ? "啟用" : "禁用", // 狀態(tài)
createTime: item.createTime // 創(chuàng)建時間
}
})
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>
表格數據導入

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">導入文件列表</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)
// 只能上傳一個Excel,重復上傳會覆蓋之前的
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["序號"]), // 序號
username: item["用戶名"], // 用戶名
roles: item["角色"], // 角色
phone: item["手機號"], // 手機號
email: item["郵箱"], // 郵箱
status: item["狀態(tài)"], // 狀態(tài)
createTime: item["創(chuàng)建時間"] // 創(chuàng)建時間
}
return newItem
})
console.log(da)
tableData.value = da
loading.value = false
}
}總結
到此這篇關于vue3純前端表格數據的導出與導入實現(xiàn)的文章就介紹到這了,更多相關vue3表格數據導出與導入內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
前端vue-cli項目中使用img圖片和background背景圖的幾種方法
這篇文章主要介紹了前端vue-cli項目中使用img圖片和background背景圖的幾種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11
Vue3.x+Element Plus仿制Acro Design簡潔模式實現(xiàn)分頁器組件
開發(fā)中難免會遇到寬度很窄的列表需要使用分頁器的情況。本文將利用Vue3.x+Element Plus仿制Acro Design簡潔模式實現(xiàn)分頁器組件,感興趣的可以了解一下2023-02-02

