poi解析xls文件demo
程序员文章站
2022-07-13 13:10:54
...
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 java.io.FileInputStream;
import java.io.IOException;
/**
* @param
* @author zhangxiaodong
* @Description: TODO poi解析Demo
* @return
* @date 2019/11/3 13:16
* @Version 1.0
*/
public class PoiExcelTest {
public static void main(String[] args)throws IOException {
//读取数据流
FileInputStream inp = new FileInputStream("项目信息.xls");
//解析工作簿
HSSFWorkbook workbook = new HSSFWorkbook(inp);
//解析工作表
//获得有多少张工作表
int size = workbook.getNumberOfSheets();
System.out.println("一共"+size+"张工作表");
HSSFSheet sheet;
HSSFRow row;
HSSFCell cell;
HSSFRow rowTou;
//循环处理读取每一个工作表中的数据
for (int i = 0; i <size ; i++) {
sheet = workbook.getSheetAt(i);
//拿到一个具体的工作表
System.out.println("读取当前工作表的名称"+sheet.getSheetName());
//得到有效行数
int rowNumber = sheet.getPhysicalNumberOfRows();
System.out.println("有效行数"+rowNumber);
for (int j = 0; j <rowNumber ; j++) {
System.out.println("正在读取第"+(j+1)+"行数据");
if(j==0){
rowTou = sheet.getRow(0);
for (int k = 0; k <rowTou.getLastCellNum() ; k++) {
HSSFCell cellLie = rowTou.getCell(k);
System.out.println("行标题:"+cellLie.getStringCellValue());
}
continue;
}
//得到行内数据
row = sheet.getRow(j);
//得到行内列数据
for (int k = 0; k < row.getLastCellNum(); k++) {
//获取每一列
cell = row.getCell(k);
//判断列值的数据类型并输出
switch (cell.getCellType()){
case HSSFCell.CELL_TYPE_NUMERIC:
System.out.println("列值:"+String.valueOf(cell.getNumericCellValue()));
break;
case HSSFCell.CELL_TYPE_STRING:
System.out.println("列值:"+cell.getStringCellValue());
break;
}
}
}
}
}
}
下一篇: POI xlsx和xls 文件操作