【01】java操作excel,循环遍历
使⽤org.apache.poi包下的HSSF相关⽅法,先后操作⼯作簿workbook、sheet、row、cell,最终定位到具体的单元格,getValue(cell)获得的都是String类型。
只取⼀⾏的时候,rowNum=1(因为rowNum=0的时候,取的是表头,也就是字段名称,不是数据);
只取⼀列的时候,cellNum=0。
取多⾏多列的时候,嵌套两个for循环即可。
ke.data;
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.IOException;
import java.io.InputStream;
import java.util.Arrays;
public class Read {
public static void main(String[] args) throws IOException {
InputStream inputStream = new FileInputStream("/Users/poi.xls");
POIFSFileSystem fs = new POIFSFileSystem(inputStream);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = SheetAt(0);  // 获取第⼀个sheet页
if (sheet == null){
return;
记住我}
// 遍历row
for (int rowNum = 1; rowNum <= LastRowNum(); rowNum++) {
HSSFRow row = Row(rowNum);
if (row==null){
continue;
}
// 遍历列cell
for (int cellNum = 0; cellNum <= LastCellNum(); cellNum++) {
HSSFCell cell = Cell(cellNum);
if (cell==null){
continue;
}
System.out.print(" "+getValue(cell));
}
System.out.println();
}
}
private static String getValue(HSSFCell cell){
if (CellType() == HSSFCell.CELL_TYPE_BOOLEAN){
return String.BooleanCellValue());
}else if (CellType() == HSSFCell.CELL_TYPE_NUMERIC){
return String.NumericCellValue());
}else {
return String.RichStringCellValue());
}
}
}
运⾏结果如下:
1.0 宋江 20.0
2.0 张三 21.0
3.0 李四 22.0
4.0 王五 23.0
5.0 朱六 24.0