需要引入jar:
org.apache.poi poi 3.11 org.apache.poi poi-ooxml 3.11 org.apache.poi poi-ooxml-schemas 3.11
直接上代码:
@Testpublic void poiTestMethod() throws Exception { String path = "/Users/zhangkai/xxx.xlsx"; //2007 //HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(path)); //2003 XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(path)); //2.获取要解析的表格(第一个表格) //0开始第一个sheet XSSFSheet sheet = wb.getSheetAt(1); //获得最后一行的行号 int lastRowNum = sheet.getLastRowNum(); for (int i = 7; i <= lastRowNum; i++) {//遍历每一行 //3.获得要解析的行 XSSFRow row = sheet.getRow(i); /** * 这个不加 不会自动转换 * 报错信息 java.lang.IllegalStateException: Cannot get a text value from a numeric cell */ row.getCell(0).setCellType(Cell.CELL_TYPE_STRING); //4.获得每个单元格中的内容(String) String stringCellValue0 = row.getCell(0).getStringCellValue(); String stringCellValue1 = row.getCell(1).getStringCellValue(); String stringCellValue2 = row.getCell(2).getStringCellValue(); String stringCellValue3 = row.getCell(3).getStringCellValue(); String stringCellValue4 = row.getCell(4).getStringCellValue(); String stringCellValue5 = row.getCell(5).getStringCellValue(); String stringCellValue6 = row.getCell(6).getStringCellValue(); String stringCellValue7 = row.getCell(7).getStringCellValue(); String stringCellValue8 = row.getCell(8).getStringCellValue(); String stringCellValue9 = row.getCell(9).getStringCellValue(); System.out.println(stringCellValue0 + "--" + stringCellValue1 + "--" + stringCellValue2 + "--" + stringCellValue3 + "--" + stringCellValue4); System.out.println(stringCellValue5 + "--" + stringCellValue6 + "--" + stringCellValue7 + "--" + stringCellValue8 + "--" + stringCellValue9); }}
可能遇到的问题:
// 报错信息 java.lang.IllegalStateException: Cannot get a text value from a numeric cell
row.getCell(j).getStringCellValue()时无法自动转换类型//获取前以下一行代码row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
Demo:
本文来自投稿,不代表本人立场,如若转载,请注明出处:http://www.souzhinan.com/kj/275228.html