136 lines
3.5 KiB
Markdown
136 lines
3.5 KiB
Markdown
# 导入导出
|
||
|
||
:::tip 说明
|
||
项目基于 `openpyxl` 实现 Excel 导入导出功能,支持通过 `file_template` 模块管理导入模板配置。路由定义在各业务模块的 router 文件中(如 `src/modules/system/user/router.py`)。
|
||
:::
|
||
|
||
## 功能概述
|
||
|
||
Excel 导入导出是后台管理系统的常见需求,通过 `openpyxl` 库实现:
|
||
|
||
```
|
||
Excel 导出:
|
||
1. 将数据库中的数据导出为 Excel 文件,支持自定义表头和格式
|
||
2. 适用于生成报表、数据备份等场景
|
||
|
||
Excel 导入:
|
||
1. 将 Excel 文件中的数据导入到数据库,支持批量处理和校验
|
||
2. 适用于批量数据录入、数据迁移等场景
|
||
```
|
||
|
||
## 依赖说明
|
||
|
||
在 `requirements.txt` 中已包含:
|
||
|
||
```
|
||
openpyxl>=3.1.0
|
||
```
|
||
|
||
## 导出实现
|
||
|
||
导出接口通常在各业务模块的 router 中定义,返回文件流:
|
||
|
||
```python
|
||
from openpyxl import Workbook
|
||
from flask import send_file
|
||
import io
|
||
|
||
@user_blue.route('/export', methods=['GET'])
|
||
@check_permission('sys:user:export')
|
||
def export():
|
||
# 查询数据
|
||
from src.modules.system.user.service import get_export_data
|
||
data_list = get_export_data()
|
||
|
||
# 创建工作簿
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.title = "用户信息"
|
||
|
||
# 写入表头
|
||
ws.append(["用户名", "姓名", "手机号", "邮箱", "状态"])
|
||
|
||
# 写入数据
|
||
for item in data_list:
|
||
ws.append([item.username, item.realname, item.phone, item.email, item.status_name])
|
||
|
||
# 返回文件流
|
||
output = io.BytesIO()
|
||
wb.save(output)
|
||
output.seek(0)
|
||
|
||
return send_file(
|
||
output,
|
||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||
as_attachment=True,
|
||
download_name="export.xlsx"
|
||
)
|
||
```
|
||
|
||
## 导入实现
|
||
|
||
导入接口接收上传的 Excel 文件,解析后逐行校验并入库:
|
||
|
||
```python
|
||
from openpyxl import load_workbook
|
||
from flask import request
|
||
|
||
@user_blue.route('/import', methods=['POST'])
|
||
@check_permission('sys:user:import')
|
||
def import_excel():
|
||
file = request.files.get('file')
|
||
if not file:
|
||
return R.failed(msg="请上传文件")
|
||
|
||
content = file.read()
|
||
wb = load_workbook(io.BytesIO(content))
|
||
ws = wb.active
|
||
|
||
# 跳过表头,逐行解析
|
||
errors = []
|
||
for row_idx, row in enumerate(ws.iter_rows(min_row=2, values_only=True), start=2):
|
||
username, realname, phone, email, status = row
|
||
# 校验并入库 ...
|
||
if error:
|
||
errors.append(f"第{row_idx}行:{error}")
|
||
|
||
if errors:
|
||
return R.failed(msg="导入失败:" + ",".join(errors))
|
||
return R.ok(msg="导入成功")
|
||
```
|
||
|
||
## file_template 模块
|
||
|
||
`file_template` 模块用于管理导入模板的配置信息,定义模板的字段映射、校验规则等。
|
||
|
||
模块路径:`src/modules/file_template/`
|
||
|
||
```
|
||
模板配置包含:
|
||
- 模板名称
|
||
- 关联模块
|
||
- 字段映射关系
|
||
- 校验规则
|
||
```
|
||
|
||
:::tip 温馨提示
|
||
导入时建议先下载模板文件,按模板格式填写数据后再导入,可减少格式错误。
|
||
:::
|
||
|
||
## 错误处理
|
||
|
||
导入过程中遇到校验错误时,返回详细的错误信息:
|
||
|
||
```json
|
||
{
|
||
"code": 1,
|
||
"msg": "导入失败:第3行用户名已存在,第5行手机号格式错误",
|
||
"data": null,
|
||
"ok": false
|
||
}
|
||
```
|
||
|
||
## 总结
|
||
|
||
Excel 导入导出功能基于 `openpyxl` 实现,导出使用 `send_file` 流式返回避免内存溢出,导入逐行校验并提供详细错误信息。`file_template` 模块可管理导入模板配置,便于维护字段映射和校验规则。
|