前端优秀文章推荐:
什么!纯前端也能识别图片中的文案、还支持100多个国家的语言
excel 的导入导出功能是前端开发中非常常见的功能,特别是在做后台管理相关的功能,导入导出excel 基本是家常便饭,有很多前端开发的同学还没做过这类需求,接到这类需求时会有些心慌,别怕,本文将介绍一款前端中最强大的导入导出插件SheetJS (xlsx),SheetJS 功能丰富且适用于各种场景
Vue3项目创建
在实现导入导出之前先创建一个vue3项目:
- 首先创建一个vue项目
pnpm create vite vue3-excel --template vue
- 安装element-plus 用来展示数据
pnpm i element-plus
- 安装 自动导入的vite插件
pnpm i -D unplugin-vue-components unplugin-auto-import
- 配置自动导入 vite.config.js
js
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
// https://vite.dev/config/
export default defineConfig({
plugins: [
vue(),
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
],
});
使用 SheetJS (xlsx)
SheetJS 是目前最强大的 JavaScript Excel 处理库,支持各种 Excel 格式和复杂操作。SheetJS 还支持跨平台,比如可以在 Web 浏览器、服务器、桌面应用程序、移动应用程序、Salesforce 和 Photoshop 插件,甚至在 Excel 中使用。
使用方式如下:
js
<template>
<div class="top-tool">
<el-button @click="exportExcelOrCsv('excel')">导出Excel</el-button>
<el-button @click="exportExcelOrCsv('csv')">导出Csv</el-button>
<el-upload
ref="uploadRef"
class="import-demo"
:auto-upload="false"
:on-change="importExcel"
>
<template #trigger>
<el-button type="primary">导入Excel或Csv</el-button>
</template>
</el-upload>
<el-upload
ref="uploadRef"
class="import-demo"
:auto-upload="false"
:on-change="importToHtml"
>
<template #trigger>
<el-button type="primary">导入生成html</el-button>
</template>
</el-upload>
</div>
<div id="excelTable"></div>
<el-table :data="products" style="width: 100%" border>
<el-table-column prop="id" label="ID" align="center" />
<el-table-column prop="name" label="商品名称" />
<el-table-column prop="category" label="分类" />
<el-table-column prop="price" label="价格" align="right">
<template #default="scope"> ¥{{ scope.row.price.toFixed(2) }} </template>
</el-table-column>
<el-table-column prop="stock" label="库存" align="center" />
<el-table-column prop="sales" label="销量" align="center" />
<el-table-column prop="status" label="状态" align="center">
<template #default="scope">
<el-tag :type="scope.row.status === '上架' ? 'success' : 'danger'">
{{ scope.row.status }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="操作" width="180" fixed="right">
<template #default="scope">
<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
<el-button size="small" type="danger" @click="handleDelete(scope.row)">
删除
</el-button>
</template>
</el-table-column>
</el-table>
</template>
<script setup>
import { ref } from "vue";
import * as XLSX from "xlsx";
const products = ref([
{
id: 1,
name: "高端智能手机",
category: "电子产品",
price: 5999.0,
stock: 120,
sales: 356,
status: "上架",
},
{
id: 2,
name: "无线蓝牙耳机",
category: "电子产品",
price: 299.0,
stock: 0,
sales: 1024,
status: "下架",
},
{
id: 3,
name: "全棉T恤",
category: "服装",
price: 89.9,
stock: 56,
sales: 234,
status: "上架",
},
{
id: 4,
name: "运动跑鞋",
category: "鞋类",
price: 399.0,
stock: 78,
sales: 189,
status: "上架",
},
]);
/**
*
* @param type 导出文件类型 excel 或这csv
*/
const exportExcelOrCsv = (type) => {
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.json_to_sheet(products.value);
XLSX.utils.book_append_sheet(wb, ws, "商品数据");
type === "excel"
? XLSX.writeFile(wb, "商品数据.xlsx")
: XLSX.writeFile(wb, "商品数据.csv");
};
const uploadRef = ref(null);
// 导入excel 或者csv
const importExcel = (e) => {
importCommon(e);
};
// 导入excel 或者csv的公共方法
const importCommon = (e, isHtml) => {
console.log("importExcel");
const file = e.raw;
const reader = new FileReader();
reader.onload = (e) => {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: "array" });
const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
if (isHtml) {
// 生成预览的html
const htmlTable = XLSX.utils.sheet_to_html(firstSheet);
document.getElementById("excelTable").innerHTML = htmlTable;
} else {
// 生成json 数据 渲染到页面
const jsonData = XLSX.utils.sheet_to_json(firstSheet);
console.log("导入数据:", jsonData);
products.value = [...jsonData, ...products.value];
}
// 处理导入数据...
};
reader.readAsArrayBuffer(file);
};
const importToHtml = (e, isHtml) => {
importCommon(e, isHtml);
};
const handleEdit = (row) => {
console.log("编辑商品", row);
// 实际项目中这里通常会打开编辑对话框
};
const handleDelete = (row) => {};
</script>
<style scoped>
.top-tool {
margin-bottom: 20px;
}
.import-demo {
display: inline-flex;
margin-left: 20px;
}
</style>
由以上可以看出导出需要以下一个步骤:
- 调用
XLSX.utils.book_new()
方法创建一个工作簿 - 调用
XLSX.utils.json_to_sheet
方法将json 数据写入到sheet中 - 调用方法
book_append_sheet
将sheet添加到工作簿,并命名 - 调用
XLSX.writeFile
方法开始写文件到文件系统
导入需要经过以下步骤:
- 利用
input type="file"
选择文件,这里用el-upload
是一样的,然后通过事件对象获取到文件信息 - 利用
FileReader
方法读取本地文件 - 调用方法
XLSX.read(data, { type: "array" })
将二进制转换为可操作的 工作簿对象(Workbook) - 通过
workbook.Sheets[workbook.SheetNames[0]]
提取具体的数据 - 最后通过
sheet_to_html
方法生成html结构(简单的table),通过sheet_to_json
生成json数据
运行效果:

点击导出excel 和导出csv

打开文件查看内容,可以看到已经将table中的数据正确导出到了excel和csv

点击导入Excel或Csv按钮 选择上面导出的excel文件,再次点击导入Excel或Csv按钮选择上面导出的csv文件可以看到数据被正常导入到页面中:

点击导入生成html 按钮,选择之前导出的csv或者excel,可以看到页面自动生成了一个html 的table结构,这在有时候非常有用,之前在工作中产品导入的时候经常会遇到一些字段比较特殊导入出现了异常,如果直接导入到了数据库就会非常麻烦。这时候我们就可以导出一个简单的html 的table预览导入显示是否正常,再进行真正的导入上传到后端。

总结
本篇主要介绍了SheetJS (xlsx) 的使用,使用SheetJS (xlsx) 可以很轻松的实现导入导出excel 或导入导出csv,导入时还可以自动生成简易的table结构,进行预览,非常方便,学会SheetJS 的使用相信你在工作中遇到excel、csv相关的操作不再会有太多困难。
本篇就分享到这里了,感谢收看