432 lines
12 KiB
Markdown
432 lines
12 KiB
Markdown
# 导入导出实现详解
|
||
|
||
> 基于 EmployeeController 和 importAndExport 示例的完整导入导出流程
|
||
> 源码分析时间:2026-04-01
|
||
|
||
---
|
||
|
||
## 一、功能概述
|
||
|
||
职员管理示例是最完整的导入导出参考,包含:
|
||
- Excel 导出(可选字段)
|
||
- Excel 导入(预览 + 确认)
|
||
- Word 导出
|
||
- PDF 导出
|
||
|
||
---
|
||
|
||
## 二、前端实现
|
||
|
||
### 2.1 API 定义(employee.ts)
|
||
|
||
```typescript
|
||
import { defHttp } from '#/api/request';
|
||
|
||
enum Api {
|
||
Prefix = '/api/extend/Employee',
|
||
}
|
||
|
||
// 获取列表
|
||
export function getEmployeeList(data) {
|
||
return defHttp.get({ url: Api.Prefix, data });
|
||
}
|
||
|
||
// 删除
|
||
export function delEmployee(id) {
|
||
return defHttp.delete({ url: `${Api.Prefix}/${id}` });
|
||
}
|
||
|
||
// 导出Excel(可选字段)
|
||
export function exportExcel(data) {
|
||
return defHttp.get({ url: `${Api.Prefix}/ExportData`, data });
|
||
}
|
||
|
||
// 模板下载
|
||
export function templateDownload() {
|
||
return defHttp.get({ url: `${Api.Prefix}/TemplateDownload` });
|
||
}
|
||
|
||
// 导入
|
||
export function importData(data) {
|
||
return defHttp.post({ url: `${Api.Prefix}/ImportData`, data });
|
||
}
|
||
|
||
// 导入预览
|
||
export function importPreview(data) {
|
||
return defHttp.get({ url: `${Api.Prefix}/ImportPreview`, data });
|
||
}
|
||
```
|
||
|
||
### 2.2 导出弹窗(ExportModal.vue)
|
||
|
||
```vue
|
||
<script lang="ts" setup>
|
||
import { ref } from 'vue';
|
||
import { useModal } from '@jnpf/ui/modal';
|
||
import { exportExcel } from '#/api/extend/employee';
|
||
import { downloadByUrl } from '@jnpf/utils';
|
||
|
||
const [registerModal, { openModal, closeModal, changeOkLoading }] = useModal();
|
||
const checkedList = ref<string[]>([]);
|
||
|
||
// 可选字段列表
|
||
const columnList = ref([
|
||
{ fullName: '工号', id: 'enCode' },
|
||
{ fullName: '姓名', id: 'fullName' },
|
||
{ fullName: '性别', id: 'gender' },
|
||
{ fullName: '部门', id: 'departmentName' },
|
||
// ...
|
||
]);
|
||
|
||
function handleSubmit() {
|
||
changeOkLoading(true);
|
||
const query = {
|
||
...listQuery.value,
|
||
dataType: dataType.value, // 0=当前页, 1=全部
|
||
selectKey: checkedList.value.join(','), // 选中的字段
|
||
};
|
||
exportExcel(query).then(res => {
|
||
downloadByUrl({ url: res.data.url });
|
||
closeModal();
|
||
}).finally(() => {
|
||
changeOkLoading(false);
|
||
});
|
||
}
|
||
</script>
|
||
|
||
<template>
|
||
<BasicModal @register="registerModal" title="导出" @ok="handleSubmit">
|
||
<!-- 导出范围 -->
|
||
<a-radio-group v-model:value="dataType">
|
||
<a-radio :value="0">当前页面数据</a-radio>
|
||
<a-radio :value="1">全部页面数据</a-radio>
|
||
</a-radio-group>
|
||
|
||
<!-- 字段选择 -->
|
||
<a-checkbox v-for="item in columnList" :key="item.id" :value="item.id">
|
||
{{ item.fullName }}
|
||
</a-checkbox>
|
||
</BasicModal>
|
||
</template>
|
||
```
|
||
|
||
### 2.3 导入弹窗(ImportModal.vue)
|
||
|
||
```vue
|
||
<script lang="ts" setup>
|
||
import { ref, reactive } from 'vue';
|
||
import { useModal } from '@jnpf/ui/modal';
|
||
import { importPreview, importData, templateDownload } from '#/api/extend/employee';
|
||
import { downloadByUrl } from '@jnpf/utils';
|
||
|
||
const state = reactive({
|
||
activeStep: 0, // 0=上传, 1=预览, 2=结果
|
||
fileName: '',
|
||
fileList: [],
|
||
list: [], // 预览数据
|
||
result: {}, // 导入结果
|
||
skipPreview: false, // 跳过预览
|
||
});
|
||
|
||
const getAction = computed(() => `${globSetting.apiURL}/api/extend/Employee/Uploader`);
|
||
|
||
function handleFileChange({ file }) {
|
||
if (file.response?.code === 200) {
|
||
state.fileName = file.response.data.name;
|
||
}
|
||
}
|
||
|
||
function handlePreview() {
|
||
importPreview({ fileName: state.fileName }).then(res => {
|
||
state.list = res.data.dataRow || [];
|
||
state.activeStep = 1;
|
||
});
|
||
}
|
||
|
||
function handleImport() {
|
||
importData({ list: state.list }).then(res => {
|
||
state.result = res.data;
|
||
state.activeStep = 2;
|
||
});
|
||
}
|
||
|
||
function handleTemplateDownload() {
|
||
templateDownload().then(res => {
|
||
downloadByUrl({ url: res.data?.url });
|
||
});
|
||
}
|
||
</script>
|
||
|
||
<template>
|
||
<BasicModal @register="registerModal" title="批量导入">
|
||
<!-- 步骤条 -->
|
||
<a-steps :current="activeStep">
|
||
<a-step title="上传文件" />
|
||
<a-step title="数据预览" />
|
||
<a-step title="导入结果" />
|
||
</a-steps>
|
||
|
||
<!-- 步骤1:上传 -->
|
||
<div v-show="activeStep === 0">
|
||
<a-upload :action="getAction" @change="handleFileChange">
|
||
<a-button>上传文件</a-button>
|
||
</a-upload>
|
||
<a-button @click="handleTemplateDownload">下载模板</a-button>
|
||
<a-switch v-model:checked="skipPreview" />
|
||
</div>
|
||
|
||
<!-- 步骤2:预览 -->
|
||
<div v-show="activeStep === 1">
|
||
<a-table :data-source="list" :columns="columns" />
|
||
</div>
|
||
|
||
<!-- 步骤3:结果 -->
|
||
<div v-show="activeStep === 2">
|
||
<p>成功: {{ result.snum }}条</p>
|
||
<p>失败: {{ result.fnum }}条</p>
|
||
</div>
|
||
</BasicModal>
|
||
</template>
|
||
```
|
||
|
||
### 2.4 主页面(index.vue)
|
||
|
||
```vue
|
||
<script lang="ts" setup>
|
||
import { useVxeTable } from '@jnpf/ui/vxeTable';
|
||
import ExportModal from './ExportModal.vue';
|
||
import ImportModal from './ImportModal.vue';
|
||
|
||
const [registerExportModal, { openModal: openExportModal }] = useModal();
|
||
const [registerImportModal, { openModal: openImportModal }] = useModal();
|
||
|
||
const [registerTable, { reload, getFetchParams }] = useVxeTable({
|
||
api: getEmployeeList,
|
||
columns,
|
||
});
|
||
|
||
function handleExport() {
|
||
openExportModal(true, { listQuery: getFetchParams() });
|
||
}
|
||
|
||
function handleImport() {
|
||
openImportModal(true, {});
|
||
}
|
||
</script>
|
||
|
||
<template>
|
||
<BasicVxeTable @register="registerTable">
|
||
<template #tableTitle>
|
||
<a-button @click="handleExport">导出</a-button>
|
||
<a-button @click="handleImport">导入</a-button>
|
||
</template>
|
||
</BasicVxeTable>
|
||
|
||
<ExportModal @register="registerExportModal" />
|
||
<ImportModal @register="registerImportModal" @reload="reload" />
|
||
</template>
|
||
```
|
||
|
||
---
|
||
|
||
## 三、后端实现
|
||
|
||
### 3.1 导出 Excel(可选字段)
|
||
|
||
```java
|
||
@GetMapping("/ExportData")
|
||
public ActionResult<DownloadVO> exportExcelData(PaginationEmployee paginationEmployee) {
|
||
String dataType = paginationEmployee.getDataType();
|
||
String selectKey = paginationEmployee.getSelectKey();
|
||
|
||
// 根据类型获取数据
|
||
List<EmployeeEntity> entityList = "0".equals(dataType)
|
||
? employeeService.getList(paginationEmployee)
|
||
: employeeService.getList();
|
||
|
||
// 构建导出数据
|
||
List<EmployeeModel> modeList = new ArrayList<>();
|
||
for (EmployeeEntity entity : entityList) {
|
||
EmployeeModel mode = new EmployeeModel();
|
||
mode.setEnCode(entity.getEnCode());
|
||
mode.setFullName(entity.getFullName());
|
||
// ... 映射字段
|
||
modeList.add(mode);
|
||
}
|
||
|
||
// 根据选中的字段构建导出列
|
||
List<ExcelExportEntity> entitys = new ArrayList<>();
|
||
String[] splitData = selectKey.split(",");
|
||
for (String key : splitData) {
|
||
if ("enCode".equals(key)) {
|
||
entitys.add(new ExcelExportEntity("工号", "enCode"));
|
||
}
|
||
if ("fullName".equals(key)) {
|
||
entitys.add(new ExcelExportEntity("姓名", "fullName"));
|
||
}
|
||
// ... 其他字段
|
||
}
|
||
|
||
// 导出
|
||
ExportParams exportParams = new ExportParams(null, "职员信息");
|
||
exportParams.setType(ExcelType.XSSF);
|
||
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, entitys, modeList);
|
||
|
||
// 上传文件
|
||
String fileName = "职员信息_" + DateUtil.dateNow("yyyyMMddHHmmss") + ".xlsx";
|
||
MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
|
||
FileInfo fileInfo = FileUploadUtils.uploadFile(
|
||
new FileParameter(FileTypeConstant.TEMPORARY, fileName), multipartFile);
|
||
|
||
// 返回
|
||
DownloadVO vo = new DownloadVO();
|
||
vo.setName(fileName);
|
||
vo.setUrl(UploaderUtil.uploaderFile(fileName + "#" + FileTypeConstant.TEMPORARY));
|
||
return ActionResult.success(vo);
|
||
}
|
||
```
|
||
|
||
### 3.2 导入预览
|
||
|
||
```java
|
||
@GetMapping("/ImportPreview")
|
||
public ActionResult<Object> importPreview(@RequestParam("fileName") String fileName) {
|
||
AtomicReference<Map<String, Object>> map = new AtomicReference<>();
|
||
FileUploadUtils.downloadFile(new FileParameter(FileTypeConstant.TEMPORARY, fileName),
|
||
inputStream -> {
|
||
// 解析 Excel
|
||
List<EmployeeModel> personList = ExcelUtil.importExcelByInputStream(
|
||
inputStream, 0, 1, EmployeeModel.class);
|
||
// 返回预览数据
|
||
map.set(employeeService.importPreview(personList));
|
||
});
|
||
return ActionResult.success(map.get());
|
||
}
|
||
```
|
||
|
||
### 3.3 导入数据
|
||
|
||
```java
|
||
@PostMapping("/ImportData")
|
||
public ActionResult<EmployeeImportVO> importData(@RequestBody EmployeeModel data) {
|
||
List<EmployeeModel> dataList;
|
||
if (data.isType()) {
|
||
// 跳过预览,直接导入
|
||
ActionResult<Object> result = importPreview(data.getFileName());
|
||
Map<String, Object> dataMap = (Map<String, Object>) result.getData();
|
||
dataList = JsonUtil.getJsonToList(dataMap.get("dataRow"), EmployeeModel.class);
|
||
} else {
|
||
dataList = data.getList();
|
||
}
|
||
|
||
// 执行导入
|
||
EmployeeImportVO result = employeeService.importData(dataList);
|
||
return ActionResult.success(result);
|
||
}
|
||
```
|
||
|
||
### 3.4 Service 导入逻辑
|
||
|
||
```java
|
||
@Override
|
||
public EmployeeImportVO importData(List<EmployeeModel> dt) {
|
||
// 日期格式处理
|
||
for (EmployeeModel model : dt) {
|
||
model.setAttendWorkTime(DateUtil.cstFormat(model.getAttendWorkTime()));
|
||
model.setBirthday(DateUtil.cstFormat(model.getBirthday()));
|
||
model.setGraduationTime(DateUtil.cstFormat(model.getGraduationTime()));
|
||
}
|
||
|
||
List<EmployeeEntity> entitys = JsonUtil.getJsonToList(dt, EmployeeEntity.class);
|
||
|
||
int sum = 0; // 成功数
|
||
int num = 0; // 失败数
|
||
List<EmployeeEntity> errList = new ArrayList<>();
|
||
|
||
for (EmployeeEntity entity : entitys) {
|
||
entity.setId(RandomUtil.uuId());
|
||
entity.setCreatorUserId(UserProvider.getLoginUserId());
|
||
entity.setCreatorTime(new Date());
|
||
try {
|
||
this.baseMapper.insert(entity);
|
||
sum++;
|
||
} catch (Exception e) {
|
||
errList.add(entity);
|
||
num++;
|
||
}
|
||
}
|
||
|
||
// 返回结果
|
||
EmployeeImportVO vo = new EmployeeImportVO();
|
||
vo.setSnum(sum);
|
||
vo.setFnum(num);
|
||
vo.setResultType(num > 0 ? 1 : 0);
|
||
if (num > 0) {
|
||
vo.setFailResult(JsonUtil.getJsonToList(errList, EmployeeModel.class));
|
||
}
|
||
return vo;
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 四、关键工具类
|
||
|
||
| 工具类 | 用途 |
|
||
|--------|------|
|
||
| `ExcelExportUtil` | EasyPOI 导出 |
|
||
| `ExcelUtil.importExcelByInputStream` | Excel 解析 |
|
||
| `UploaderUtil.uploaderFile` | 文件上传 |
|
||
| `FileUploadUtils.uploadFile` | 文件存储 |
|
||
| `DateUtil.cstFormat` | 日期格式转换 |
|
||
|
||
---
|
||
|
||
## 五、文件上传接口
|
||
|
||
```java
|
||
@PostMapping("/Uploader")
|
||
public ActionResult<DownloadVO> uploader() {
|
||
List<MultipartFile> list = UpUtil.getFileAll();
|
||
MultipartFile file = list.get(0);
|
||
if (!file.isEmpty()) {
|
||
String fileName = RandomUtil.uuId() + "." + UpUtil.getFileType(file);
|
||
FileInfo fileInfo = FileUploadUtils.uploadFile(
|
||
new FileParameter(FileTypeConstant.TEMPORARY, fileName), file);
|
||
DownloadVO vo = new DownloadVO();
|
||
vo.setName(fileInfo.getFilename());
|
||
return ActionResult.success(vo);
|
||
}
|
||
return ActionResult.fail(MsgCode.ETD110.get());
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 六、导入导出结果模型
|
||
|
||
```java
|
||
@Data
|
||
public class EmployeeImportVO {
|
||
private Integer snum; // 成功数量
|
||
private Integer fnum; // 失败数量
|
||
private Integer resultType; // 结果类型 0=全部成功, 1=部分失败
|
||
private List<EmployeeModel> failResult; // 失败数据
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 七、完整流程图
|
||
|
||
```
|
||
导出:
|
||
用户点击导出 → 打开导出弹窗 → 选择范围和字段 → 调用 ExportData
|
||
→ Service 查询数据 → 构建 Excel → 上传文件 → 返回下载地址
|
||
|
||
导入:
|
||
用户点击导入 → 打开导入弹窗 → 上传文件 → 调用 Uploader
|
||
→ 文件上传到临时目录 → 调用 ImportPreview → 预览数据
|
||
→ 用户确认 → 调用 ImportData → Service 批量插入 → 返回结果
|
||
```
|