1、工具类加载xlsx文件
public class DemoUtils { public static Workbook readExcel(String filePath) { Workbook wb = null; if (filePath == null) { return null; } String extString = filePath.substring(filePath.lastIndexOf(".")); InputStream is = null; try { is = new FileInputStream(filePath); if (".xls".equals(extString)) { return wb = new HSSFWorkbook(is); } else if (".xlsx".equals(extString)) { return wb = new XSSFWorkbook(is); } else { return wb = null; } } catch (Exception e) { e.printStackTrace(); } return wb; } }
2、获取数据
public class XXl { public static List<String> getString() { List<String> result = new ArrayList<String>(); Workbook book = DemoUtils.readExcel("C:\\Users\\Administrator\\Desktop\\1.xlsx"); int numberOfSheets = book.getNumberOfSheets(); for (int number = 0; number < numberOfSheets; number++) { Sheet sheet = book.getSheetAt(number); System.out.println(sheet.getSheetName()); // 输出该表格的名称 // 遍历所有行 for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { Row row = sheet.getRow(rowNum); if (row == null) { continue; } int col = row.getPhysicalNumberOfCells(); for (int j = 0; j < col; j++) { Cell cell = row.getCell(j); //判断该单元格是字符串还是数字类型 String cellType = cell.getCellType().toString(); if ("STRING".equals(cellType)) { System.out.println("第" + (rowNum + 1) + "行,第" + (j + 1) + "列的值是:》》》" + cell.getRichStringCellValue().getString()); result.add(cell.getRichStringCellValue().getString()); } else if ("NUMERIC".equals(cellType)) { NumberFormat ddf1=NumberFormat.getNumberInstance(); ddf1.setMaximumFractionDigits(0); System.out.println( "第" + (rowNum + 1) + "行,第" + (j + 1) + "列的值是:》》》" + ddf1.format(cell.getNumericCellValue())); result.add(String.valueOf(ddf1.format(cell.getNumericCellValue()))); } } } } return result; } public static void main(String[] args) { List<String> string = getString(); for (String s : string) { System.out.print(s); } } }
3、所需jar
<dependencies> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.1</version> </dependency> </dependencies>