安装
yarn add xlsx
效果图
代码环境
vue3.0 +ts
代码
<template>
<!-- tablecommon -->
<div class="commonBoxmp white-bg">
<Table
class="roletable-table"
:tableData="state.tableData"
:searchBool="false"
:column="state.column"
@getCurrentColumns="getCurrentColumns"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:pagination="state.page"
>
<template #tableLeft>
<h3 class="mx15">xlsx转json 读取文件注意当前文件字符集 当前字符集GB2312</h3>
</template>
<template #tableColumn>
<el-table-column
v-for="(item, index) in state.columnData"
class="animate__animated animate__fadeInUp"
:key="index"
:label="item.label"
:prop="item.prop"
>
</el-table-column>
</template>
<template #tableRight>
<div>
<el-upload
:limit="1"
:auto-upload="false"
:show-file-list="false"
class="upload-demo mx15"
:on-change="handleChange"
>
<el-button size="small" type="primary">选取xlsx</el-button>
</el-upload>
</div>
</template>
</Table>
</div>
</template>
<script setup lang="ts">
import { forIn } from "@antv/x6/lib/util/object/object";
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import xml from "xlsx";
import type { LltColumn } from "/@ts/views/sys/account/column";
const router = useRouter();
const route = useRoute();
//
onMounted(() => {});
/*
基本数据类型
引用数据类型(复杂类型) 个人建议 ref初始化变量
ref 和 reactive 本质我们可以简单的理解为ref是对reactive的二次包装,
ref定义的数据访问的时候要多一个.value
*/
const count = ref(0);
const state: any = reactive({
column: [],
tableData: [],
page:{
currentPage: 1,
total: 0,
pageSize: 10,
pageSizes: [10, 15, 20],
}
});
const handleCurrentChange = (num: number) => {
state.tableData = [];
};
//解析表
const readWorkbook = (workbook: any) => {
var sheetNames = workbook.SheetNames; // 工作表名称集合
let dataJson: any = [];
sheetNames.forEach((element: any) => {
var worksheet2 = workbook.Sheets[element];
var jsonArr = xml.utils.sheet_to_json(worksheet2);
dataJson.push(jsonArr);
});
return dataJson[0]; //这里为了展示读取第一张表 需要多张表自行处理
};
const handleChange = (e: any) => {
readWorkbookFromLocalFile(e.raw, (workbook: any) => {
let adddataJson = readWorkbook(workbook);
let column: LltColumn[] = [];
let element = adddataJson[0];
for (const key in adddataJson[0]) {
if (Object.prototype.hasOwnProperty.call(element, key)) {
column.push({
label: key,
prop: key,
show: true,
});
}
}
state.column = column;
state.columnData = column;
state.tableData = adddataJson;
state.page.total = adddataJson.length
});
};
//读区文件
const readWorkbookFromLocalFile = (file: any, callback: any) => {
try {
var reader = new FileReader();
reader.onload = function (e: any) {
var data = e.target.result;
var workbook = xml.read(data, {
type: "string",
});
if (callback) callback(workbook);
};
reader.readAsText(file, "GB2312");//读取文件字符集
} catch (e) {
console.error("xml解析出问题");
throw "xml解析出问题";
}
};
const handleSizeChange = (size: number) => {};
const getCurrentColumns = (data: LltColumn[]) => {
// console.log("data :>> ", data);
state.columnData = data;
};
</script>
<style scoped lang="scss"></style>