怎么做企业网站推广,做网站广告联盟赚钱,买模板建设网站,福州绿光网站建设工作室导出#xff1a;解析excel 二进制文件
https://blog.csdn.net/weixin_43746297/article/details/146204040
导入#xff1a;解析excel 二进制文件
解析#xff1a;
注意#xff1a;使用前需通过npm install xlsx安装依赖库
动态表头生成 使用 sheet_to_json 的 header…导出解析excel 二进制文件
https://blog.csdn.net/weixin_43746297/article/details/146204040
导入解析excel 二进制文件
解析
注意使用前需通过npm install xlsx安装依赖库
动态表头生成 使用 sheet_to_json 的 header:1 参数提取首行作为表头 Excel工作表转换为JSON格式
const jsonData XLSX.utils.sheet_to_json(firstSheet, {header: 1,raw: false, //保留公式defval:
})
参数配置如下 header: 指定输出结果为二维数组格式每行数据以数组形式呈现。若不设置该参数或设为其他值则默认输出键值对格式的对象数组。 raw: false 保留单元格原始公式而非计算结果适用于需要获取Excel公式的场景。若设为true则输出公式计算结果。 defval: 为空单元格设置默认值为空字符串避免解析时跳过空值导致字段缺失。未设置时默认会忽略空单元格。
jsonData结构取决于header参数
当header:1时结果为ArrayArrayany每行数据为子数组默认情况结果为ArrayObject首行作为键名
典型应用场景包括
前端导入带公式的Excel表格需要严格保留空单元格位置的表格处理复杂表头数据的结构化转换
使用xlsx库读取Excel数据
const workbook XLSX.read(data, {type: array,cellFormula: true,cellHTML: false});
主要功能如下
type: array参数表示输入数据是Uint8Array类型的二进制数组cellFormula: true会保留Excel单元格中的公式信息而不是只获取计算结果cellHTML: false表示不需要将单元格内容转换为HTML格式
workbook对象包含属性
SheetNames属性工作表名称列表Sheets对象包含各个工作表数据
典型使用场景包括
前端导入带公式的Excel文件需要保留原始公式而非计算结果的场景
从接口中获取
1.封装接口方法 获取excel字节流
封装示例 封装方法调用方法和传参形式依照自己的这里只是示例 注意responseType: arraybuffer 必填*** 调用方法 exportHandover({传参:传参}).then((res) {// 获取到二进制流 res}).catch((err) {//弹出错误信息});这里是解析二进制流之后的数据格式 可自定义可查看 下方完整代码 arr.push({sheetName,columns: headers.map((h, i) ({prop: col${i},label: h})),list: [{columns: headers.map((h, i) ({prop: col${i},label: h})),data: dataRows.map(row {return headers.reduce((obj, header, idx) {obj[col${idx}] row[idx] || return obj}, {})})}]})
完整代码
此段代码适用于 excel 单文件/多文件
templatediv classlayout-padding w100div classlayout-padding-auto layout-padding-viewel-tabs styleheight: calc(100% - 50px) v-modelactiveFile typecardel-tab-panev-forfile in fileData:keyfile.sheetName:labelfile.sheetName:namefile.sheetNameclasstable-containerel-table:datafile.listborder:header-cell-style{ borderColor: #C0C0C0,textAlign:center }:cell-style{ borderColor: #C0C0C0,textAlign:center }el-table-columnv-forcol in file.columns:keycol.prop:propcol.prop:labelcol.label//el-table/el-tab-pane/el-tabs/div/div
/templatescript setup langts nameteam
import {useI18n} from vue-i18n;
import {reactive, ref, onMounted} from vue;
import {viewDeta} from //stores/viewDeta;
import {exportHandover} from //api/shiftHandover;
import {downBlobFile} from //utils/other;
import {ElLoading} from element-plus;
import * as XLSX from xlsx;
import {useMessage} from //hooks/message;const stores viewDeta();
// 引入组件
const {t} useI18n();
// 定义变量内容
const editFormDialog ref();
const fileData ref()
const activeFile ref()
const queryForm reactive({yearMonth: new Date().toISOString().slice(0, 7),deptId: ,roleId: ,
})
const getDeptData () {if (stores.$state.rolesName ! undefined) {const loading ElLoading.service({lock: true,text: 数据加载中...,background: rgba(5,5,5,0.6),})exportHandover({参数}).then((res) {const data new Uint8Array(res)loading.close()const workbook XLSX.read(data, {type: array,cellFormula: true,cellHTML: false});let arr []workbook.SheetNames.forEach((sheetName) {const firstSheet workbook.Sheets[sheetName]const jsonData XLSX.utils.sheet_to_json(firstSheet, {header: 1,raw: false,defval: })const headers jsonData[0] || []const dataRows jsonData.slice(1)arr.push({sheetName,columns: headers.map((h, i) ({prop: col${i},label: h})),list: [{columns: headers.map((h, i) ({prop: col${i},label: h})),data: dataRows.map(row {return headers.reduce((obj, header, idx) {obj[col${idx}] row[idx] || return obj}, {})})}]})})arr.map((item) {item.list item.list.flatMap(r r.data)})fileData.value arractiveFile.value fileData.value[0].sheetName}).catch((err) {useMessage().error(err.msg);loading.close()});}
};onMounted(() {
});
/script
style scoped langscss
.table-container {display: flex;flex-direction: column;height: 100%; /* 或父容器高度 */
}.table-container .el-table {flex: 1;min-height: 0; /* 关键属性 */
}
/style结果 2.ajax方法直接获取
接口路径/api/excel 使用axios时需设置 responseType: arraybuffer 或blob接收二进制流 const res await axios.get(/api/excel, {responseType: arraybuffer
});
完整代码
此代码适用于单文件如需多文件 参考上方封装接口方法
templatedivbutton clickloadExcelData加载Excel数据/buttontable v-iftableData.lengththeadtrth v-forcol in columns :keycol.key{{ col.title }}/th/tr/theadtbodytr v-for(row, rowIndex) in tableData :keyrowIndextd v-forcol in columns :keycol.key{{ row[col.key] }}/td/tr/tbody/table/div
/templatescript setup
import { ref } from vue;
import axios from axios;
import * as XLSX from xlsx;// 表格数据和列配置
const tableData ref([]);
const columns ref([]);// 从接口加载Excel数据
const loadExcelData async () {try {// 1. 请求二进制数据关键responseType: arraybufferconst response await axios.get(https://your-api.com/excel, {responseType: arraybuffer});// 2. 解析Excelconst data new Uint8Array(response.data);const workbook XLSX.read(data, { type: array });const firstSheet workbook.Sheets[workbook.SheetNames[0]];// 3. 提取表头假设第一行为表头const headerRow XLSX.utils.sheet_to_json(firstSheet, { header: 1 })[0];columns.value headerRow.map(key ({key,title: key}));// 4. 提取表格数据tableData.value XLSX.utils.sheet_to_json(firstSheet);} catch (error) {console.error(加载失败:, error);}
};
/script上传文件获取
此方法适用于excel中单文件如excel中多文件 请参考上方 封装接口方法 templatedivel-uploadmultiple:auto-uploadfalse:on-changehandleFileChangeaccept.xlsx,.xlsel-button typeprimary选择多个Excel文件/el-button/el-uploadel-table v-for(table, index) in tables :keyindex:datatable.databorderstylemargin-top:20pxel-table-columnv-forcol in table.columns:keycol.prop:propcol.prop:labelcol.label:formattercol.formatter//el-table/div
/templatescript setup
import { ref } from vue
import * as XLSX from xlsxconst tables ref([])const handleFileChange async (files) {tables.value []for (const file of files) {const buffer await file.raw.arrayBuffer()const workbook XLSX.read(buffer, { type: array,cellFormula: true // 保留公式})workbook.SheetNames.forEach(sheetName {const worksheet workbook.Sheets[sheetName]const jsonData XLSX.utils.sheet_to_json(worksheet, {header: 1,raw: false,defval: })if(jsonData.length 0) {const columns jsonData[0].map((header, idx) ({prop: col${idx},label: header || 列${idx1},formatter: (row) {const cellRef XLSX.utils.encode_cell({r: row.__rowNum__, c: idx})return worksheet[cellRef]?.f ? XLSX.utils.sheet_to_json(worksheet, {header:1})[row.__rowNum__][idx] :row[col${idx}]}}))const data jsonData.slice(1).map((row, rowIndex) {const rowObj { __rowNum__: rowIndex 1 }row.forEach((cell, colIndex) {rowObj[col${colIndex}] cell})return rowObj})tables.value.push({name: ${file.name}-${sheetName},columns,data})}})}
}
/script