mirror of
https://github.com/vbenjs/vue-vben-admin.git
synced 2025-08-27 15:41:32 +08:00
feat(excel): import/export (#40)
This commit is contained in:
6
src/components/Excel/index.ts
Normal file
6
src/components/Excel/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export { default as ImportExcel } from './src/ImportExcel';
|
||||
export { default as ExportExcelModel } from './src/ExportExcelModel.vue';
|
||||
|
||||
export { jsonToSheetXlsx, aoaToSheetXlsx } from './src/Export2Excel';
|
||||
|
||||
export * from './src/types';
|
57
src/components/Excel/src/Export2Excel.ts
Normal file
57
src/components/Excel/src/Export2Excel.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import xlsx from 'xlsx';
|
||||
import type { WorkBook } from 'xlsx';
|
||||
import type { JsonToSheet, AoAToSheet } from './types';
|
||||
// import { isObject } from '@/src/utils/is';
|
||||
|
||||
const { utils, writeFile } = xlsx;
|
||||
|
||||
export function jsonToSheetXlsx<T = any>({
|
||||
data,
|
||||
header,
|
||||
filename = 'excel-list.xlsx',
|
||||
json2sheetOpts = {},
|
||||
write2excelOpts = { bookType: 'xlsx' },
|
||||
}: JsonToSheet<T>) {
|
||||
const arrData = [...data];
|
||||
if (header) {
|
||||
arrData.unshift(header);
|
||||
json2sheetOpts.skipHeader = true;
|
||||
}
|
||||
|
||||
const worksheet = utils.json_to_sheet(arrData, json2sheetOpts);
|
||||
|
||||
/* add worksheet to workbook */
|
||||
const workbook: WorkBook = {
|
||||
SheetNames: [filename],
|
||||
Sheets: {
|
||||
[filename]: worksheet,
|
||||
},
|
||||
};
|
||||
/* output format determined by filename */
|
||||
writeFile(workbook, filename, write2excelOpts);
|
||||
/* at this point, out.xlsb will have been downloaded */
|
||||
}
|
||||
export function aoaToSheetXlsx<T = any>({
|
||||
data,
|
||||
header,
|
||||
filename = 'excel-list.xlsx',
|
||||
write2excelOpts = { bookType: 'xlsx' },
|
||||
}: AoAToSheet<T>) {
|
||||
const arrData = [...data];
|
||||
if (header) {
|
||||
arrData.unshift(header);
|
||||
}
|
||||
|
||||
const worksheet = utils.aoa_to_sheet(arrData);
|
||||
|
||||
/* add worksheet to workbook */
|
||||
const workbook: WorkBook = {
|
||||
SheetNames: [filename],
|
||||
Sheets: {
|
||||
[filename]: worksheet,
|
||||
},
|
||||
};
|
||||
/* output format determined by filename */
|
||||
writeFile(workbook, filename, write2excelOpts);
|
||||
/* at this point, out.xlsb will have been downloaded */
|
||||
}
|
79
src/components/Excel/src/ExportExcelModel.vue
Normal file
79
src/components/Excel/src/ExportExcelModel.vue
Normal file
@@ -0,0 +1,79 @@
|
||||
<template>
|
||||
<BasicModal v-bind="$attrs" title="导出数据" @ok="handleOk" @register="registerModal">
|
||||
<BasicForm
|
||||
:labelWidth="100"
|
||||
:schemas="schemas"
|
||||
:showActionButtonGroup="false"
|
||||
@register="registerForm"
|
||||
/>
|
||||
</BasicModal>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
import { defineComponent } from 'vue';
|
||||
import { BasicModal, useModalInner } from '/@/components/Modal';
|
||||
import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
|
||||
|
||||
const schemas: FormSchema[] = [
|
||||
{
|
||||
field: 'filename',
|
||||
component: 'Input',
|
||||
label: '文件名',
|
||||
rules: [{ required: true }],
|
||||
},
|
||||
{
|
||||
field: 'bookType',
|
||||
component: 'Select',
|
||||
label: '文件类型',
|
||||
defaultValue: 'xlsx',
|
||||
rules: [{ required: true }],
|
||||
componentProps: {
|
||||
options: [
|
||||
{
|
||||
label: 'xlsx',
|
||||
value: 'xlsx',
|
||||
key: 'xlsx',
|
||||
},
|
||||
{
|
||||
label: 'html',
|
||||
value: 'html',
|
||||
key: 'html',
|
||||
},
|
||||
{
|
||||
label: 'csv',
|
||||
value: 'csv',
|
||||
key: 'csv',
|
||||
},
|
||||
{
|
||||
label: 'txt',
|
||||
value: 'txt',
|
||||
key: 'txt',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
];
|
||||
export default defineComponent({
|
||||
components: { BasicModal, BasicForm },
|
||||
setup(_, { emit }) {
|
||||
const [registerForm, { validateFields }] = useForm();
|
||||
const [registerModal, { closeModal }] = useModalInner();
|
||||
|
||||
async function handleOk() {
|
||||
const res = await validateFields();
|
||||
const { filename, bookType } = res;
|
||||
|
||||
emit('success', {
|
||||
filename: `${filename.split('.').shift()}.${bookType}`,
|
||||
bookType,
|
||||
});
|
||||
closeModal();
|
||||
}
|
||||
return {
|
||||
schemas,
|
||||
handleOk,
|
||||
registerForm,
|
||||
registerModal,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
120
src/components/Excel/src/ImportExcel.tsx
Normal file
120
src/components/Excel/src/ImportExcel.tsx
Normal file
@@ -0,0 +1,120 @@
|
||||
import { defineComponent, ref, unref } from 'vue';
|
||||
import XLSX from 'xlsx';
|
||||
import { getSlot } from '/@/utils/helper/tsxHelper';
|
||||
|
||||
import type { ExcelData } from './types';
|
||||
export default defineComponent({
|
||||
name: 'ImportExcel',
|
||||
setup(_, { slots, emit }) {
|
||||
const inputRef = ref<HTMLInputElement | null>(null);
|
||||
const loadingRef = ref<Boolean>(false);
|
||||
|
||||
/**
|
||||
* @description: 第一行作为头部
|
||||
*/
|
||||
function getHeaderRow(sheet: XLSX.WorkSheet) {
|
||||
if (!sheet || !sheet['!ref']) return [];
|
||||
const headers: string[] = [];
|
||||
// A3:B7=>{s:{c:0, r:2}, e:{c:1, r:6}}
|
||||
const range = XLSX.utils.decode_range(sheet['!ref']);
|
||||
|
||||
const R = range.s.r;
|
||||
/* start in the first row */
|
||||
for (let C = range.s.c; C <= range.e.c; ++C) {
|
||||
/* walk every column in the range */
|
||||
const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })];
|
||||
/* find the cell in the first row */
|
||||
let hdr = 'UNKNOWN ' + C; // <-- replace with your desired default
|
||||
if (cell && cell.t) hdr = XLSX.utils.format_cell(cell);
|
||||
headers.push(hdr);
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description: 获得excel数据
|
||||
*/
|
||||
function getExcelData(workbook: XLSX.WorkBook) {
|
||||
const excelData: ExcelData[] = [];
|
||||
for (const sheetName of workbook.SheetNames) {
|
||||
const worksheet = workbook.Sheets[sheetName];
|
||||
const header: string[] = getHeaderRow(worksheet);
|
||||
const results = XLSX.utils.sheet_to_json(worksheet);
|
||||
excelData.push({
|
||||
header,
|
||||
results,
|
||||
meta: {
|
||||
sheetName,
|
||||
},
|
||||
});
|
||||
}
|
||||
return excelData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description: 读取excel数据
|
||||
*/
|
||||
function readerData(rawFile: File) {
|
||||
loadingRef.value = true;
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = async (e) => {
|
||||
try {
|
||||
const data = e.target && e.target.result;
|
||||
const workbook = XLSX.read(data, { type: 'array' });
|
||||
// console.log(workbook);
|
||||
/* DO SOMETHING WITH workbook HERE */
|
||||
const excelData = getExcelData(workbook);
|
||||
emit('success', excelData);
|
||||
resolve();
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
} finally {
|
||||
loadingRef.value = false;
|
||||
}
|
||||
};
|
||||
reader.readAsArrayBuffer(rawFile);
|
||||
});
|
||||
}
|
||||
|
||||
async function upload(rawFile: File) {
|
||||
const inputRefDom = unref(inputRef);
|
||||
if (inputRefDom) {
|
||||
// fix can't select the same excel
|
||||
inputRefDom.value = '';
|
||||
}
|
||||
readerData(rawFile);
|
||||
}
|
||||
/**
|
||||
* @description: 触发选择文件管理器
|
||||
*/
|
||||
function handleInputClick(e: Event) {
|
||||
const files = e && (e.target as HTMLInputElement).files;
|
||||
const rawFile = files && files[0]; // only use files[0]
|
||||
if (!rawFile) return;
|
||||
upload(rawFile);
|
||||
}
|
||||
/**
|
||||
* @description: 点击上传按钮
|
||||
*/
|
||||
function handleUpload() {
|
||||
const inputRefDom = unref(inputRef);
|
||||
inputRefDom && inputRefDom.click();
|
||||
}
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<div>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept=".xlsx, .xls"
|
||||
style=" z-index: -9999; display: none;"
|
||||
onChange={handleInputClick}
|
||||
/>
|
||||
<div onClick={handleUpload}>{getSlot(slots)}</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
30
src/components/Excel/src/types.ts
Normal file
30
src/components/Excel/src/types.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import type { JSON2SheetOpts, WritingOptions, BookType } from 'xlsx';
|
||||
|
||||
export interface ExcelData<T = any> {
|
||||
header: string[];
|
||||
results: T[];
|
||||
meta: { sheetName: string };
|
||||
}
|
||||
|
||||
// export interface ImportProps {
|
||||
// beforeUpload: (file: File) => boolean;
|
||||
// }
|
||||
|
||||
export interface JsonToSheet<T = any> {
|
||||
data: T[];
|
||||
header?: T;
|
||||
filename?: string;
|
||||
json2sheetOpts?: JSON2SheetOpts;
|
||||
write2excelOpts?: WritingOptions;
|
||||
}
|
||||
export interface AoAToSheet<T = any> {
|
||||
data: T[][];
|
||||
header?: T[];
|
||||
filename?: string;
|
||||
write2excelOpts?: WritingOptions;
|
||||
}
|
||||
|
||||
export interface ExportModalResult {
|
||||
filename: string;
|
||||
bookType: BookType;
|
||||
}
|
@@ -66,6 +66,20 @@ const menu: MenuModule = {
|
||||
path: '/strength-meter',
|
||||
name: '密码强度组件',
|
||||
},
|
||||
{
|
||||
path: '/excel',
|
||||
name: 'excel',
|
||||
children: [
|
||||
{
|
||||
path: '/export',
|
||||
name: 'Export',
|
||||
},
|
||||
{
|
||||
path: '/import',
|
||||
name: 'Import',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
@@ -136,5 +136,31 @@ export default {
|
||||
title: '密码强度组件',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: '/excel',
|
||||
name: 'ExcelDemo',
|
||||
redirect: '/comp/excel/export',
|
||||
meta: {
|
||||
title: 'excel',
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: 'export',
|
||||
name: 'Export2Excel',
|
||||
component: () => import('/@/views/demo/comp/excel/ExportToExcel.vue'),
|
||||
meta: {
|
||||
title: 'Export2Excel',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'import',
|
||||
name: 'ImportExcel',
|
||||
component: () => import('/@/views/demo/comp/excel/ImportExcel.vue'),
|
||||
meta: {
|
||||
title: 'ImportExcel',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
} as AppRouteModule;
|
||||
|
79
src/views/demo/comp/excel/ExportToExcel.vue
Normal file
79
src/views/demo/comp/excel/ExportToExcel.vue
Normal file
@@ -0,0 +1,79 @@
|
||||
<template>
|
||||
<div>
|
||||
<BasicTable title="基础表格" :columns="columns" :dataSource="data">
|
||||
<template #toolbar>
|
||||
<a-button @click="openModal">JSON格式导出:默认头部</a-button>
|
||||
<a-button @click="customHeader">JSON格式导出:自定义头部</a-button>
|
||||
<a-button @click="aoaToExcel">二维数组格式导出</a-button>
|
||||
</template>
|
||||
</BasicTable>
|
||||
<ExportExcelModel @register="register" @success="defaultHeader" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent } from 'vue';
|
||||
import { BasicTable } from '/@/components/Table';
|
||||
import {
|
||||
jsonToSheetXlsx,
|
||||
aoaToSheetXlsx,
|
||||
ExportExcelModel,
|
||||
ExportModalResult,
|
||||
} from '/@/components/Excel';
|
||||
import { columns, data, arrHeader, arrData } from './data';
|
||||
import { useModal } from '/@/components/Modal';
|
||||
|
||||
export default defineComponent({
|
||||
components: { BasicTable, ExportExcelModel },
|
||||
setup() {
|
||||
function defaultHeader({ filename, bookType }: ExportModalResult) {
|
||||
// 默认Object.keys(data[0])作为header
|
||||
jsonToSheetXlsx({
|
||||
data,
|
||||
filename,
|
||||
write2excelOpts: {
|
||||
bookType,
|
||||
},
|
||||
});
|
||||
}
|
||||
function customHeader() {
|
||||
jsonToSheetXlsx({
|
||||
data,
|
||||
header: {
|
||||
id: 'ID',
|
||||
name: '姓名',
|
||||
age: '年龄',
|
||||
no: '编号',
|
||||
address: '地址',
|
||||
beginTime: '开始时间',
|
||||
endTime: '结束时间',
|
||||
},
|
||||
filename: '文件名头部修改.xlsx',
|
||||
json2sheetOpts: {
|
||||
// 指定顺序
|
||||
header: ['name', 'id'],
|
||||
},
|
||||
});
|
||||
}
|
||||
function aoaToExcel() {
|
||||
// 保证data顺序与header一致
|
||||
aoaToSheetXlsx({
|
||||
data: arrData,
|
||||
header: arrHeader,
|
||||
filename: '数组方式导出excel.xlsx',
|
||||
});
|
||||
}
|
||||
const [register, { openModal }] = useModal();
|
||||
|
||||
return {
|
||||
defaultHeader,
|
||||
customHeader,
|
||||
aoaToExcel,
|
||||
columns,
|
||||
data,
|
||||
register,
|
||||
openModal,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
56
src/views/demo/comp/excel/ImportExcel.vue
Normal file
56
src/views/demo/comp/excel/ImportExcel.vue
Normal file
@@ -0,0 +1,56 @@
|
||||
<template>
|
||||
<div>
|
||||
<ImportExcel @success="loadDataSuccess">
|
||||
<a-button class="m-3">导入Excel</a-button>
|
||||
</ImportExcel>
|
||||
<BasicTable
|
||||
v-for="(table, index) in tableListRef"
|
||||
:key="index"
|
||||
:title="table.title"
|
||||
:columns="table.columns"
|
||||
:dataSource="table.dataSource"
|
||||
></BasicTable>
|
||||
</div>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
import { defineComponent, ref } from 'vue';
|
||||
|
||||
import { ImportExcel, ExcelData } from '/@/components/Excel';
|
||||
import { BasicTable, BasicColumn } from '/@/components/Table';
|
||||
|
||||
export default defineComponent({
|
||||
components: { BasicTable, ImportExcel },
|
||||
|
||||
setup() {
|
||||
const tableListRef = ref<
|
||||
{
|
||||
title: string;
|
||||
columns?: any[];
|
||||
dataSource?: any[];
|
||||
}[]
|
||||
>([]);
|
||||
|
||||
function loadDataSuccess(excelDataList: ExcelData[]) {
|
||||
tableListRef.value = [];
|
||||
console.log(excelDataList);
|
||||
for (const excelData of excelDataList) {
|
||||
const {
|
||||
header,
|
||||
results,
|
||||
meta: { sheetName },
|
||||
} = excelData;
|
||||
const columns: BasicColumn[] = [];
|
||||
for (const title of header) {
|
||||
columns.push({ title, dataIndex: title });
|
||||
}
|
||||
tableListRef.value.push({ title: sheetName, dataSource: results, columns });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
loadDataSuccess,
|
||||
tableListRef,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
59
src/views/demo/comp/excel/data.ts
Normal file
59
src/views/demo/comp/excel/data.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { BasicColumn } from '/@/components/Table';
|
||||
|
||||
export const columns: BasicColumn[] = [
|
||||
{
|
||||
title: 'ID',
|
||||
dataIndex: 'id',
|
||||
width: 80,
|
||||
},
|
||||
{
|
||||
title: '姓名',
|
||||
dataIndex: 'name',
|
||||
width: 120,
|
||||
},
|
||||
{
|
||||
title: '年龄',
|
||||
dataIndex: 'age',
|
||||
width: 80,
|
||||
},
|
||||
{
|
||||
title: '编号',
|
||||
dataIndex: 'no',
|
||||
width: 80,
|
||||
},
|
||||
{
|
||||
title: '地址',
|
||||
dataIndex: 'address',
|
||||
},
|
||||
{
|
||||
title: '开始时间',
|
||||
dataIndex: 'beginTime',
|
||||
},
|
||||
{
|
||||
title: '结束时间',
|
||||
dataIndex: 'endTime',
|
||||
},
|
||||
];
|
||||
|
||||
export const data: any[] = (() => {
|
||||
const arr: any[] = [];
|
||||
for (let index = 0; index < 40; index++) {
|
||||
arr.push({
|
||||
id: `${index}`,
|
||||
name: `${index} John Brown`,
|
||||
age: `${index + 10}`,
|
||||
no: `${index}98678`,
|
||||
address: 'New York No. 1 Lake ParkNew York No. 1 Lake Park',
|
||||
beginTime: new Date().toLocaleString(),
|
||||
endTime: new Date().toLocaleString(),
|
||||
});
|
||||
}
|
||||
return arr;
|
||||
})();
|
||||
|
||||
// ["ID", "姓名", "年龄", "编号", "地址", "开始时间", "结束时间"]
|
||||
export const arrHeader = columns.map((column) => column.title);
|
||||
// [["ID", "姓名", "年龄", "编号", "地址", "开始时间", "结束时间"],["0", "0 John Brown", "10", "098678"]]
|
||||
export const arrData = data.map((item) => {
|
||||
return Object.keys(item).map((key) => item[key]);
|
||||
});
|
Reference in New Issue
Block a user