poi 将Excel数据导入到数据库中 第三版

接第二版
将第二版导出的数据导入到数据库中

java代码

@SpringBootTest(classes = {ShujiegouApplication.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class PoiInsertDataBase {

    @Autowired
    private SysColumnService sysColumnService;

    List<SysColumn> sysColumnAll = new ArrayList<>();

//    public void test(MultipartFile file) throws Exception {
//        InputStream inputStream = file.getInputStream();
    @Test
    public void test2() throws Exception {
//        1.读取文件
        FileInputStream fileInputStream = new FileInputStream(new File("E://gurua.xls"));
//        2.解析流得到工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
//        3.获取表
//        HSSFSheet sheet = workbook.getSheetAt(0); //根据下标获取表
        HSSFSheet sheet = workbook.getSheet("guru");    //根据表名获取表
//        4.获取行 1----最后一行
        int lastRowNum = sheet.getLastRowNum();
//        5.获取数据封装在集合中
        for (int i = 1; i <= lastRowNum; i++) {
            SysColumn sysColumn = new SysColumn();
//            获取行
            HSSFRow row = sheet.getRow(i);

//            获取单元格和数据
            HSSFCell cell0 = row.getCell(0);
            double numericCellValue = cell0.getNumericCellValue();
            int id = (int) numericCellValue;
            sysColumn.setId(id);

            HSSFCell cell1 = row.getCell(1);
            String columnName = cell1.getStringCellValue();
            sysColumn.setColumnName(columnName);

            HSSFCell cell2 = row.getCell(2);
            double numericCellValue2 = cell2.getNumericCellValue();
            int parentId = (int) numericCellValue2;
            sysColumn.setParentId(parentId);

            HSSFCell cell3 = row.getCell(3);
            double numericCellValue3 = cell3.getNumericCellValue();
            int columnRank = (int) numericCellValue3;
            sysColumn.setColumnRank(columnRank);

            HSSFCell cell4 = row.getCell(4);
            String stringCellValue = cell4.getStringCellValue();
            sysColumn.setEnName(stringCellValue);

//            封装好的对象放入集合
            sysColumnAll.add(sysColumn);
        }

//        6.添加数据库
        for (SysColumn sysColumn : sysColumnAll) {
            System.out.println(sysColumn);
            sysColumnService.insert(sysColumn);
        }
    }
}

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "sys_column")
public class SysColumn {

    @Id
    private Integer id;
    private String columnName;
    private Integer parentId;
    private Integer columnRank;
    private String enName;

}

数据库截图
在这里插入图片描述
这辈子坚持与不坚持都不可怕,怕的是独自走在坚持的道路上!

欢迎加入技术群聊

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/taiguolaotu/article/details/107046427