签入版本
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
# 导入导出
|
||||
|
||||
:::tip 说明
|
||||
基于 `openpyxl` 实现 Excel 导入导出功能,支持通过 `file_template` 模块管理导入模板配置。端点定义在各业务模块的 endpoint 文件中(如 `src/modules/user.py`)。
|
||||
:::
|
||||
|
||||
## 功能概述
|
||||
|
||||
Excel 导入导出是后台管理系统的常见需求,通过 `openpyxl` 库实现:
|
||||
|
||||
```
|
||||
Excel 导出:
|
||||
1. 将数据库中的数据导出为 Excel 文件,支持自定义表头和格式
|
||||
2. 适用于生成报表、数据备份等场景
|
||||
|
||||
Excel 导入:
|
||||
1. 将 Excel 文件中的数据导入到数据库,支持批量处理和校验
|
||||
2. 适用于批量数据录入、数据迁移等场景
|
||||
```
|
||||
|
||||
## 依赖说明
|
||||
|
||||
在 `requirements.txt` 中已包含:
|
||||
|
||||
```
|
||||
openpyxl>=3.1.0
|
||||
```
|
||||
|
||||
## 导出实现
|
||||
|
||||
导出接口通常在各业务模块的 Handler 中定义,返回文件流:
|
||||
|
||||
```python
|
||||
from openpyxl import Workbook
|
||||
import io
|
||||
|
||||
class UserExportHandler(BaseHandler):
|
||||
@permission_required("sys:user:export")
|
||||
async def get(self):
|
||||
# 查询数据
|
||||
data_list = user_service.get_export_data(self)
|
||||
|
||||
# 创建工作簿
|
||||
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)
|
||||
|
||||
self.set_header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
self.set_header("Content-Disposition", "attachment; filename=export.xlsx")
|
||||
self.finish(output.getvalue())
|
||||
```
|
||||
|
||||
## 导入实现
|
||||
|
||||
导入接口接收上传的 Excel 文件,解析后逐行校验并入库:
|
||||
|
||||
```python
|
||||
class UserImportHandler(BaseHandler):
|
||||
@permission_required("sys:user:import")
|
||||
@check_demo
|
||||
async def post(self):
|
||||
file = self.request.files.get('file', [None])[0]
|
||||
if not file:
|
||||
return R.failed(self, "请上传文件")
|
||||
wb = load_workbook(io.BytesIO(file.body))
|
||||
ws = wb.active
|
||||
|
||||
# 跳过表头,逐行解析
|
||||
for row in ws.iter_rows(min_row=2, values_only=True):
|
||||
username, realname, phone, email, status = row
|
||||
# 校验并入库 ...
|
||||
```
|
||||
|
||||
## file_template 模块
|
||||
|
||||
`file_template` 模块用于管理导入模板的配置信息,定义模板的字段映射、校验规则等。
|
||||
|
||||
模块路径:`src/modules/file_template/`
|
||||
|
||||
```
|
||||
模板配置包含:
|
||||
- 模板名称
|
||||
- 关联模块
|
||||
- 字段映射关系
|
||||
- 校验规则
|
||||
```
|
||||
|
||||
:::tip 温馨提示
|
||||
导入时建议先下载模板文件,按模板格式填写数据后再导入,可减少格式错误。
|
||||
:::
|
||||
|
||||
## 错误处理
|
||||
|
||||
导入过程中遇到校验错误时,返回详细的错误信息:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 1,
|
||||
"msg": "导入失败:第3行用户名已存在,第5行手机号格式错误",
|
||||
"data": null,
|
||||
"ok": false
|
||||
}
|
||||
```
|
||||
|
||||
## 总结
|
||||
|
||||
Excel 导入导出功能基于 `openpyxl` 实现,导出通过 `self.finish()` 返回文件流避免内存溢出,导入逐行校验并提供详细错误信息。`file_template` 模块可管理导入模板配置,便于维护字段映射和校验规则。
|
||||
Reference in New Issue
Block a user