meven项目,导包
org.apache.poi
poi-ooxml
4.1.2
小案例
package com.offcn.poitest;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import java.util.Iterator;
public class PoiTest {
//java程序读取Excel文件的内容 -- Excel导入操作
@Test
public void test1() throws Exception{
//读取文件 -- 工作薄对象
XSSFWorkbook sheets = new XSSFWorkbook("C:\Users\24634\Desktop\cjw.xlsx");
//读表 -- 表对象
Iterator iterator = sheets.iterator();
while (iterator.hasNext()){
//获取到sheet
Sheet sheet = iterator.next();
//判断sheet是否为空,如果为空就直接下一个
if (sheet == null){
continue;
}
//读行 -- 行对象
Iterator rowIterator = sheet.iterator();
while (rowIterator.hasNext()){
Row row = rowIterator.next();
//当行对象为空的时候直接跳过
if (row == null){
continue;
}
//读单元格 -- 单元格对象
Iterator| cellIterator = row.iterator();
while (cellIterator.hasNext()) {
//获取到每个单元格对象
Cell cell = cellIterator.next();
//判断单元格对象是否为空
if (cell == null) continue;
//获取值
CellType cellType = cell.getCellType();
String name = cellType.name();
//System.out.println(cellType.name());
if ("STRING".equals(name)){
//获取到时STRING类型的单元格中的值
String value = cell.getStringCellValue();
System.out.println(value);
}else if ("NUMERIC".equals(name)){
double value = cell.getNumericCellValue();
System.out.println(value);
}
}
}
}
//释放资源
sheets.close();
}
}
|