Java 导入接口(poi)

1.在pom文件中添加poi依赖:

复制代码
<!--poi-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
复制代码

2.主要代码

(1)student类

复制代码
import lombok.Data;

@Data
public class Student {
    private String id;
    private String name;
    private int age;
    private String birthday;
    private String school;
    private String mother;
    private String createTime;
    private int pageNum;
    private int pageSize;
}
复制代码

(2)controller层

复制代码
/**
     * 通过导入excel文件,读出每个单元格的内容。
     * InputStream来自于文件上传时的MultipartFile对象
     */
    @ApiOperation("季测评-导入接口")
    @PostMapping(value = "importSeasonTest")
    public ResponseEntity<Object> importSeasonTest(@RequestParam MultipartFile file,
                                                   @RequestParam String name){
        return ResponseEntity.ok(uploadService.importSeasonTest(file,name));
    }
复制代码

 

(3)service层

复制代码
public Object importSeasonTest(MultipartFile file, String name) {
        String[] WAGES_HEAD_CH = {"姓名", "年龄", "生日", "学校", "父母"};//表头
        String[] WAGES_HEAD_EN = {"name", "age", "birthday", "school", "mother"};//表头对应参数
        List<Map<String, String>> dataList = ExcelUpload.upload(file, WAGES_HEAD_CH, WAGES_HEAD_EN);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

        List<Student> studentList = new ArrayList<>();
        for (Map<String, String> item : dataList) {
            Student student = new Student();
            student.setName(name);
            student.setBirthday(item.get("birthday"));
            student.setAge((int) Double.parseDouble(item.get("age")));
            student.setSchool(item.get("school"));
            student.setMother(item.get("mother"));
            student.setCreateTime(df.format(new Date()));
            studentList.add(student);
        }
        int insertCount = uploadMapper.addStudentData(studentList);
        return insertCount;
    }
复制代码

 

(4)Mapper层

 int addStudentData(List<Student> studentList);

 

(5)xml层

复制代码
 <insert id="addStudentData">
        insert into
        student (
        id,
        name,
        age,
        birthday,
        school,
        mother,
        create_time
        )values
        <foreach collection="list" item="item" index="index" separator="," >
            (
            replace(uuid(), '-', ''),
            #{item.name},
            #{item.age},
            #{item.birthday},
            #{item.school},
            #{item.mother},
            #{item.createTime}
            )
        </foreach>
    </insert>
复制代码

(6)配置文件ExcelUpload 

复制代码
import com.example.demo.exception.CustomException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelUpload {
    public static List<Map<String, String>> upload(MultipartFile file, String[] WAGES_HEAD_CH, String[] WAGES_HEAD_EN) {

        List<Map<String, String>> rows = new ArrayList<>();
        //获取文件名称
        String fileName = file.getOriginalFilename();
        try {
            //获取输入流
            InputStream in = file.getInputStream();
            //判断excel版本
            Workbook workbook = null;
            if (ExcelUtil.judegExcelEdition(fileName)) {
                workbook = new XSSFWorkbook(in);
            } else {
                workbook = new HSSFWorkbook(in);
            }
            //获取第一张工作表
            Sheet sheet = workbook.getSheetAt(0);

            //获取表头(第一行)
            Row row0 = sheet.getRow(0);
            if (WAGES_HEAD_CH.length != row0.getPhysicalNumberOfCells()) {
                throw new CustomException("导入的excel表头不正确(名称错误)");
            }
            for (int i = 0; i < WAGES_HEAD_CH.length; i++) {
                if (!WAGES_HEAD_CH[i].equals(String.valueOf(row0.getCell(i)))) {
                    throw new CustomException("导入的excel表头不正确(名称错误)");
                }
            }
            //从第二行开始获取
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                //获取每一行
                Row sheetRow = sheet.getRow(i);
                Map<String, String> m = new HashMap<>();
                for (int j = 0; j < WAGES_HEAD_EN.length; j++) {
                    if (sheetRow.getCell(j) != null) {
                        m.put(WAGES_HEAD_EN[j], String.valueOf(sheetRow.getCell(j)));
                    }
                }
                rows.add(m);
            }
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rows;
    }
}
复制代码

 

(7)配置文件ExcelUtil 

复制代码
public class ExcelUtil {
    public static boolean judegExcelEdition(String fileName){
        if (fileName.matches("^.+\\.(?i)(xls)$")){
            return false;
        }else {
            return true;
        }
    }
}
复制代码

3.postman测试结果(http://localhost:端口号/file/importSeasonTest)

 4.数据库结果

   final:不积跬步,无以至千里.不积小流,无以成江海

posted @   krt-wanyi  阅读(1608)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示