由于在例子中使用了lambda表达式,所以需要确保jdk 在 1.8 以上
<build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.8</source><target>1.8</target></configuration></plugin></plugins></build><dependencies><!-- 读取Excel 文件相关jar包 --><!-- https://mvnrepository.com/artifact/nz.ac.waikato.cms.weka/WekaExcel --><dependency><groupId>nz.ac.waikato.cms.weka</groupId><artifactId>WekaExcel</artifactId><version>1.0.6</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>RELEASE</version></dependency></dependencies>
小demo:
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 org.junit.Test;
import java.io.FileInputStream;
import java.io.InputStream;public class TestHSSFWorkbook{@Testpublic void workbookTest() {HSSFWorkbook hssfWorkbook = null;InputStream is = null;try {// 目标xls文件String path = this.getClass().getResource("/XXX.xls").getPath();is = new FileInputStream(path);hssfWorkbook = new HSSFWorkbook(new POIFSFileSystem(is));HSSFSheet sheet = hssfWorkbook.getSheetAt(0);// 非lambda表达式HSSFRow row = null;for(int i = 0; i < sheet.getLastRowNum(); i++) {row = sheet.getRow(i);for(int j = 0; j < row.getLastCellNum(); j++) {System.out.print(row.getCell(j) + "|");}System.out.println();}// lambda 表达式sheet.forEach(r -> {r.forEach(c -> System.out.print(c.getStringCellValue() + "|"));System.out.println();});} catch (Exception e) {e.printStackTrace();}}
}
上面这个小小例子只是做了一个遍历,并没有什么复杂操作,感觉HSSFSheet这个结构类似于二维数组,但是它其实内部有一个 TreeMap<Integer, HSSFRow> _rows, HSSFRow 中存放着 HSSFCell[] cells,HSSFWorkbook 存放sheet : List _sheets。