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;

}

數據庫截圖
在這裏插入圖片描述
這輩子堅持與不堅持都不可怕,怕的是獨自走在堅持的道路上!

歡迎加入技術羣聊

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章