java poi cell_java poi学习 Excel的读取与写

importorg.apache.poi.hssf.usermodel.HSSFCell;importorg.apache.poi.hssf.usermodel.HSSFDateUtil;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.ss.usermodel.Cell;importorg.apache.poi.ss.usermodel.Row;importorg.apache.poi.ss.usermodel.Sheet;importorg.apache.poi.ss.usermodel.Workbook;importorg.joda.time.DateTime;importjava.io.FileInputStream;importjava.io.InputStream;importjava.util.Date;public classDemo1 {public static void main(String[] args) throwsException {

String fileName= "E:\\static\\poi\\测试工作簿.xls";

readExcel(fileName);

}public static void readExcel(String fileName) throwsException {//读取文件

InputStream inputStream = newFileInputStream(fileName);//找到工作簿

Workbook workbook = newHSSFWorkbook(inputStream);//找到对应的表格Sheet,0表示第一sheet

Sheet sheet = workbook.getSheetAt(0);//得到物理行数

int rowCount =sheet.getPhysicalNumberOfRows();//根据物理行数,读取每一格的内容

for (int rowNum = 0; rowNum < rowCount; rowNum++) {//读取每一行的内容

Row rowData =sheet.getRow(rowNum);//空指针判断

if (rowData != null) {//得到物理列数,总共有多少列

int cellCount =rowData.getPhysicalNumberOfCells();//读取每个单元格的数据

for (int cellNum = 0; cellNum < cellCount; cellNum++) {//读取了数据是cell对象//cell对象有多个数据类型

Cell cell =rowData.getCell(cellNum);//空指针判断

if (cell != null) {//获取当前单元格的数据类型

int cellType =cell.getCellType();//最终读取的值

String cellValue = "";//根据单元格数据类型来读取数据

switch(cellType) {//字符串类型

caseHSSFCell.CELL_TYPE_STRING:

System.out.print("字符串类型数据:");//字符串类型数据获取方法

cellValue =cell.getStringCellValue();break;//布尔类型,一般不会见到这个类型的值

caseHSSFCell.CELL_TYPE_BOOLEAN:

System.out.print("布尔类型的数据:");//布尔类型数据获取方法

cellValue =String.valueOf(cell.getBooleanCellValue());break;//空数据

caseHSSFCell.CELL_TYPE_BLANK:

System.out.print("为空的数据:");break;//数值类型//数值类型一共有两种,时间戳和数值

caseHSSFCell.CELL_TYPE_NUMERIC://判断当前的数值是否是一个时间戳

if(HSSFDateUtil.isCellDateFormatted(cell)) {

System.out.print("日期:");//时间数据类型转换

Date date =cell.getDateCellValue();

cellValue= new DateTime(date).toString("yyyy-MM-dd HH:mm:ss");

}else{//不是日期格式,则防止当数字过长时以科学计数法显示

System.out.print("数值类型的数据:");//数值类型的数据转换成字符串类型

cell.setCellType(HSSFCell.CELL_TYPE_STRING);

cellValue=cell.toString();

}break;//公式类型的数据

caseHSSFCell.CELL_TYPE_FORMULA://得到单元格使用的公式

String formula =cell.getCellFormula();

System.out.print("单元格使用的公式是:" +formula);//得到计算的数据

double value =cell.getNumericCellValue();

System.out.print("计算的数据为:" +value);break;//错误的数据类型

caseCell.CELL_TYPE_ERROR:

System.out.print("数据类型错误");break;

}

System.out.println(cellValue);

}

}

}

}

inputStream.close();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值