fastapi+vue实现导入Excel表格的功能

1.前端部分

1.1 api设置

// 导入用户
export function uploadUser(data) {
  const formData = new FormData();
  formData.append('file', data);  // data 是从文件上传事件中获取的文件对象
  return request({
    url: '/users/upload',
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data: formData,
    transformRequest: [(data) => data]  // 禁用默认的序列化行为
  })
}

1.2 导入按钮

      <el-upload
        class="upload-demo"
        ref="upload"
        action="dummy-action"
        :show-file-list="false" :before-upload="handleImportUser">
        <el-button type="primary" icon="el-icon-download" style="margin-left: 20px">导入</el-button>
      </el-upload>

1.3 按钮点击事件调用接口

    // 导入的回调
    async handleImportUser(file) {
      if (!file.name.endsWith('.xlsx')) return this.$message.error('请上传Excel文件!')
      if (file.size > 1024 * 1024 * 5) return this.$message.error('文件大小不能超过5MB!')
      const res = await uploadUser(file)
      if (res.code !== 200) return this.$message.error('导入失败!')
      this.$message.success('导入成功!')
      this.getUserList()
    }

2. 后端部分

@user_router.post('/upload', summary='导入用户')
async def user_upload(file: UploadFile):
    # 检查文件类型是否为 Excel
    if not file.filename.endswith(('.xls', '.xlsx')):
        return base_response(code=400, msg='文件格式错误!')
    if file.size > 1024 * 1024 * 5:
        return base_response(code=400, msg='文件大小不能超过5MB!')

    # 读取 Excel 文件
    wb = openpyxl.load_workbook(file.file)
    ws = wb.active

    # 遍历 Excel 表格的每一行数据并保存到数据库中
    for row in ws.iter_rows(min_row=2, values_only=True):  # Assuming first row is header
        try:
            name, nick_name, phone, password = row
            # 数据校验
            if not name or not password:
                raise ValueError('姓名和密码不能为空!')
            if await User.exists(name=name):
                raise ValueError('用户已存在!')
            if not re.match(r'^1[3-9]\d{9}$', str(phone)):
                raise ValueError('手机号码格式错误!')

            # 将有效数据保存到数据库中,这里假设有一个数据库操作函数 save_user()
            await User.create(name=name, nick_name=nick_name, phone=phone, password=hash_password(str(password)))
        except ValueError as e:
            print(f"数据导入失败:{e}")

    return base_response(code=200, msg='导入用户成功!')

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现 excel 数据导入功能,需要完成以下步骤: 1. 前端页面实现文件上传功能,可以使用 vue-upload-component 组件实现。 2. 后端使用 Spring Boot 框架,导入 poi 依赖,使用 poi 解析 Excel 文件,获取数据并保存到数据库中。 下面是具体的实现步骤: 1. 前端页面 在 vue 组件中,使用 vue-upload-component 组件实现文件上传功能。具体实现代码如下: ``` <template> <div> <input type="file" ref="file" @change="handleFileChange"> <button @click.prevent="submit">上传</button> </div> </template> <script> import UploadComponent from 'vue-upload-component' export default { components: { UploadComponent }, data () { return { file: null } }, methods: { handleFileChange () { this.file = this.$refs.file.files[0] }, submit () { const formData = new FormData() formData.append('file', this.file) this.$http.post('/upload', formData) .then(res => { console.log(res) }) .catch(err => { console.log(err) }) } } } </script> ``` 2. 后端实现 2.1 添加依赖 在 Spring Boot 项目的 pom.xml 文件中添加 poi 依赖: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> ``` 2.2 实现文件上传接口 在 Spring Boot 项目中,实现文件上传的接口: ``` @PostMapping("/upload") public void upload(MultipartFile file) throws Exception { Workbook workbook = WorkbookFactory.create(file.getInputStream()); Sheet sheet = workbook.getSheetAt(0); List<Data> dataList = new ArrayList<>(); for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); if (row == null) { continue; } Data data = new Data(); data.setName(row.getCell(0).getStringCellValue()); data.setAge((int) row.getCell(1).getNumericCellValue()); dataList.add(data); } dataRepository.saveAll(dataList); } ``` 其中,Data 是保存数据的实体类,dataRepository 是数据访问接口。 3. 完整示例 前端页面代码: ``` <template> <div> <input type="file" ref="file" @change="handleFileChange"> <button @click.prevent="submit">上传</button> </div> </template> <script> import UploadComponent from 'vue-upload-component' export default { components: { UploadComponent }, data () { return { file: null } }, methods: { handleFileChange () { this.file = this.$refs.file.files[0] }, submit () { const formData = new FormData() formData.append('file', this.file) this.$http.post('/upload', formData) .then(res => { console.log(res) }) .catch(err => { console.log(err) }) } } } </script> ``` 后端代码: ``` @RestController public class ExcelController { @Autowired private DataRepository dataRepository; @PostMapping("/upload") public void upload(MultipartFile file) throws Exception { Workbook workbook = WorkbookFactory.create(file.getInputStream()); Sheet sheet = workbook.getSheetAt(0); List<Data> dataList = new ArrayList<>(); for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); if (row == null) { continue; } Data data = new Data(); data.setName(row.getCell(0).getStringCellValue()); data.setAge((int) row.getCell(1).getNumericCellValue()); dataList.add(data); } dataRepository.saveAll(dataList); } } @Entity public class Data { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Integer age; // getter and setter } ``` 注意,需要在 application.properties 中配置数据库连接等信息。另外,需要在 Vue 项目中使用 axios 来发送请求。 这样,就完成了 Spring Boot + Vue 实现 excel 数据导入功能的示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值