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:不积跬步,无以至千里.不积小流,无以成江海


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM