选择excel文件并写入数据库

package com.example.excel.controller;

import com.example.excel.entity.Student;
import com.example.excel.service.StudentService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/stu")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/html")
    public String go() {
        return "/upload";
    }

    @RequestMapping("/upload")
    public String upload(@RequestParam("test") MultipartFile file) throws IOException, InvalidFormatException {
        if (file.getOriginalFilename().isEmpty()) {
            return "/fail";
        }
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String name = UUID.randomUUID().toString().replaceAll("-", "");
        String fileName = name + suffix;
        String newPath = StudentController.class.getResource("/").getPath();
        this.uploadFile(file, newPath.substring(1), fileName);
        File file1 = new File(newPath + fileName);
        Workbook sheets = WorkbookFactory.create(file1);
        Sheet sheet = sheets.getSheetAt(0);
        for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
            Row row = sheet.getRow(i);
            Student student = new Student();
            String[] str = new String[row.getLastCellNum()];
            for (int j = 0; j < row.getLastCellNum(); j++) {
                Cell cell = row.getCell(j);//取得第j列数据
                cell.setCellType(CellType.STRING);
                str[j] = cell.getStringCellValue().trim();
            }
            student.setSName(str[0]);
            student.setSAge(Integer.parseInt(str[1]));
            student.setSSex(Integer.parseInt(str[2]));
            this.studentService.insert(student);
        }
        sheets.close();
        if (file1.exists()) {
            file1.delete();
        }
        return "/success";
    }

    public String uploadFile(MultipartFile file, String path, String fileName) throws IOException {
        // 判断路径是否存在,不存在则创建
        File filePath = new File(path);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        String newFilePath = path + "\\" + fileName; //新文件的路径
        file.transferTo(new File(newFilePath));  //将传来的文件写入新建的文件
        return newFilePath;
    }

}

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>

    <form action="/stu/upload" method="POST" enctype="multipart/form-data">
        文件:<input type="file" name="test" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
        <input type="submit"/>
    </form>

</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值