POI的入门学习(二)遍历工作簿的行和列输出单元格内容
引入依赖
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency>
提前准备的excel表格内容
Demo代码
package cn.jp.poi.demo.test; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import java.io.FileInputStream; import java.io.InputStream; /** * @author JP * @title: Demo4 * @projectName demoPoi * @description: 遍历excel输出内容 * @date 2019/5/13 0013 */ public class Demo4 { public static void main(String[] args) throws Exception { //文件输入流导入excel文件 InputStream inputStream=new FileInputStream("c:\\demo3.xls"); POIFSFileSystem fileSystem=new POIFSFileSystem(inputStream); HSSFWorkbook workbook=new HSSFWorkbook(fileSystem); HSSFSheet sheet=workbook.getSheetAt(0); //获取第一个sheet页 if (sheet==null){ return; } //遍历行Row System.out.println(sheet.getLastRowNum()); for(int i=0;i<=sheet.getLastRowNum();i++){ HSSFRow row=sheet.getRow(i); //获取单行 if (row==null){ return; } //遍历列 for(int j=0;j<=row.getLastCellNum();j++){ HSSFCell cell=row.getCell(j); //获取单列 if(cell ==null){ continue; } System.out.print(" "+getValue(cell)); } System.out.println(); } } private static String getValue(HSSFCell cell){ if(cell.getCellType() ==HSSFCell.CELL_TYPE_BOOLEAN){ //若为boolean类型 return String.valueOf(cell.getBooleanCellValue()); }else if (cell.getCellType() ==HSSFCell.CELL_TYPE_NUMERIC){ //若为数字类型 return String.valueOf(cell.getNumericCellValue()); }else { return String.valueOf(cell.getStringCellValue()); //其他类型统一返回字符串 } } }
输出结果