test.xlsx:
Code:
package poi; import static org.junit.Assert.*; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value=Parameterized.class) public class TestIterator { public TestIterator(Integer times) { } @Parameters public static Collection<Integer[]> init(){ int times=200; Integer[][] parameters=new Integer[times][1]; for (int i = 0; i < times; i++) { parameters[i][0]=i; } return Arrays.asList(parameters); } @Test public void testItertor() throws IOException{ List<Integer> expected=new ArrayList<Integer>();//rowNums.need to change according to demand for (int i = 0; i <=1 ; i++) { expected.add(i); } expected.add(3); expected.add(4); expected.add(6); List<Integer> actual=new ArrayList<Integer>(); String filePath="/poi/test.xlsx"; InputStream is=this.getClass().getResourceAsStream(filePath); Workbook wb=new XSSFWorkbook(is); Sheet sheet=wb.getSheetAt(0); for (Row row : sheet) { actual.add(row.getRowNum()); } assertEquals(expected, actual); } }
结果:通过验证。
源码解析:
org.apache.poi.xssf.usermodel.XSSFSheet
XSSFRow的存放数据结构:
private TreeMap<Integer, XSSFRow> _rows;
/** * @return an iterator of the PHYSICAL rows. Meaning the 3rd element may not * be the third row if say for instance the second row is undefined. * Call getRowNum() on each row if you care which one it is. */ @SuppressWarnings("unchecked") public Iterator<Row> rowIterator() { return (Iterator<Row>)(Iterator<? extends Row>) _rows.values().iterator(); } /** * Alias for {@link #rowIterator()} to * allow foreach loops */ public Iterator<Row> iterator() { return rowIterator(); }
时间: 2024-10-19 17:07:41