Poi use in conjunction with a Java implementation of key bulk import excel

Apache is operable to provide poi api ms office document formats, Poi binding paper describes the use of Java code to achieve a key bulk import excel, the suffix can operate both formats excel.

First import jar package

Maven way

<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>

Here the main import for four exam excel file
excel:
Here Insert Picture Description
SQL:

    <insert id="exportWordList">
        insert into wordmp.word_record(name,soundmark,explainword,rank) values
        <foreach collection='list' item='word' separator=','>
            (#{word.name},#{word.soundmark},#{word.explainword},4)
        </foreach>
    </insert>

Dao:

@Repository
public interface TestDao {
     void exportWordList(@RequestParam List<WordRecord> wordRecords);
}

Realization of post-processing file excel read readExcelUtils.readExcel

    @ApiOperation(value = "导入题库测试",notes = "导入题库测试")
    @PostMapping("/exportWord")
    public Response<?> exportWord(@RequestParam MultipartFile upfile){
        try {
            InputStream inputStream = upfile.getInputStream();
            String filename = upfile.getOriginalFilename();
            if (filename == ""|| filename == null){
                throw new BaseException("请选择文件");

            }
            if (!filename.matches("^.+\\.(?i)(xlsx|xls)$")){
                return Response.failure("文件格式不对");
            }
            List<Map<String, Object>> list = ExcelUtils.readExcel(filename, inputStream);
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = objectMapper.writeValueAsString(list);
            List<WordRecord> wordRecordList = objectMapper.readValue(jsonStr, new TypeReference<List<WordRecord>>() {
            });
            //将读取后并转化了的数据批量导入
            testService.exportWordList(wordRecordList);
            return Response.success("导入成功");
        } catch (IOException e) {
            return Response.error(e);
        }
    }

ExcelUtils. : Code has detailed notes

/**
 * @progarm: Poiexport
 * @author: Leox
 * @create: 2020-1-14 10:46
 * @description:
 */

public class ExcelUtils {
    public static List<Map<String, Object>> readExcel(String fileName, InputStream inputStream) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        // 判断文件名是否合法
        boolean ret = isXls(fileName);
        //1.读取工作簿
        Workbook workbook = null;
		// 两种结构 HSSF 与 XSSF 选择
        if (ret == true) {
            workbook = new HSSFWorkbook(inputStream);
        } else {
            workbook = new XSSFWorkbook(inputStream);
        }
   		//得到工作表
        Sheet sheet = workbook.getSheetAt(0);
		//得到行,0表示第一行
        Row row = sheet.getRow(0);
        // 获取row里面最后一个单元格编号
        short lastCellNum = row.getLastCellNum();
        // 获取最后一行的行号
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++) {
            Map<String, Object> map = new HashMap<>();
            Row row1 = sheet.getRow(i);
            for (int j= 0;j<lastCellNum;j++) {
            	//创建单元格行号由row确定,列号作为参数传递给createCell;第一列从0开始计算
                Cell cell = row1.getCell(j);
                if (cell == null) {
                    continue;
                }
                cell.setCellType(CellType.STRING);
                //System.out.println(cell.getStringCellValue());
				//获取单元格值
                map.put(row.getCell(j).getStringCellValue(), cell.getStringCellValue());
            }
            list.add(map);
        }
        return list;

    }

    private  static boolean isXls(String filename) {
        if (filename.matches("^.+\\.(?i)(xls)$")) {
            return true;
        }else if(fileName.matches("^.+\\.(?i)(xlsx)$")){
			return false; 
        else {
            throw new RuntimeException("格式不对");
        }
    }
}

Execution :
Here Insert Picture Description
Last import was successful:
Here Insert Picture Description

Published 20 original articles · won praise 36 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_41426763/article/details/103969288