spring boot導入excel文件讀取內容寫入數據庫

.xls需要引入poi
.xlsx需要引入poi-ooxml

		<!--pom.xml文件引入poi依賴-->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.10-FINAL</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.10-FINAL</version>
		</dependency>
public void importTerminalGroupFile(Map<String, Object> search) {
        String fileName = StrUtils.toString(search.get("fileName"));
        String base64 = StrUtils.toString(search.get("file"));
        
        [base64文件流轉MultipartFile](https://blog.csdn.net/hcg012/article/details/102395540)
        
        MultipartFile multipartFile = base64ToMultipart(base64);
        try {
            InputStream inputStream = multipartFile.getInputStream();
            //進行版本選擇解析方式
            Workbook wb = null;
            if (fileName.endsWith(".xlsx")) {
                wb = new XSSFWorkbook(inputStream);

            } else if (fileName.endsWith(".xls")) {
                wb = new HSSFWorkbook(inputStream);
            }
            Sheet sheet = wb.getSheetAt(0);
            int rowNum = sheet.getLastRowNum() + 1;
            //行循環開始
            for (int i = 1; i < rowNum; i++) {
                //行
                Row row = sheet.getRow(i);
                //每行的最後一個單元格位置
                int cellNum = row.getLastCellNum();
                String cellValue = null;
                //列循環開始
                for (int j = 0; j < cellNum; j++) {

                    Cell cell = row.getCell(Short.parseShort(j + ""));
                    if (null != cell) {
                        // 判斷excel單元格內容的格式,並對其進行轉換,以便插入數據庫
                        switch (cell.getCellType()) {
                            case HSSFCell.CELL_TYPE_NUMERIC:
                                cellValue = cell.getNumericCellValue() + ",";
                                break;
                            case HSSFCell.CELL_TYPE_STRING:
                                cellValue = StrUtils.trim(cell.getStringCellValue()) + ",";
                                break;
                            case HSSFCell.CELL_TYPE_FORMULA:
                                break;
                            default:
                                cellValue = ",";
                                break;
                        }
                    } else {
                        cellValue = ",";
                    }

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