Using an example of data read excel poi
Two cases:
A method of reading the value of a specified cell
Another is to read the value of the entire row
Dependencies:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
Code Example:
public String getCellFromExcel(String path, String row, String col) throws Exception { return getCellFromExcel(path, 0, Integer.valueOf(row), Integer.valueOf(col)); } public String getRowFromExcel(String path, String row) throws Exception { return getRowFromExcel(path, 0, Integer.valueOf(row)); } public String getRowFromExcel(String path, int sheet, int row) throws Exception { File xlsx = new File(path); Workbook workbook = WorkbookFactory.create(xlsx); Sheet sheet1 = workbook.getSheetAt(sheet); Row row1 = sheet1.getRow(row); List<String> list = new ArrayList<>(); int rowNum = row1.getLastCellNum(); for (int i = 0; i < rowNum; i++) { list.add(getCellValueByCell(row1.getCell(i))); } logger.info("文件名:{},sheet:{},row:{},取值:{}", path, sheet, row, list.toString()); return list.toString(); } public String getCellFromExcel(String path, int sheet, int row, int col) throws Exception { File xlsx = new File(path); Workbook workbook = WorkbookFactory.create(xlsx); Sheet sheet1 = workbook.getSheetAt(sheet); Row row1 = sheet1.getRow(row); String cell = getCellValueByCell(row1.getCell(col)); logger.info("文件名:{},sheet:{},row:{},col:{},取值:{}", path, sheet, row, col, cell); return cell; } // Get the value of various types of cells, returns a string type Private static String getCellValueByCell (the Cell Cell) { // determines whether an empty string is null or IF (Cell == null || cell.toString (). TRIM (). The equals ( "" )) { return "" ; } String CellValue = "" ; int celltype = cell.getCellType (); // the following are types of data judgment Switch (celltype) { Case HSSFCell.CELL_TYPE_NUMERIC: // digital IF (0 cell.getCellType == ()) { // type determining cell type is NUMERIC or if (HSSFDateUtil.isCellDateFormatted(cell)) {// 判断是否为日期类型 Date date = cell.getDateCellValue(); DateFormat formater = new SimpleDateFormat( "yyyy-MM-dd HH:mm"); cellValue = formater.format(date); } else { cellValue = cell.getNumericCellValue() + ""; } } break; case HSSFCell.CELL_TYPE_STRING: // 字符串 cellValue = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean cellValue = cell.getBooleanCellValue() + ""; break; case HSSFCell.CELL_TYPE_FORMULA: // 公式 cellValue = cell.getCellFormula() + ""; break; case HSSFCell.CELL_TYPE_BLANK: // 空值 cellValue = ""; break; case HSSFCell.CELL_TYPE_ERROR: //Fault cellValue = "illegal character" ; BREAK ; default : CellValue = "Unknown type" ; BREAK ; } return CellValue; }