package com.huateng.common.grid;
import java.io.FileInputStream;
import java.io.InputStream;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;/**
* @author syl
* @version 创建时间:2019年4月20日 上午10:42:35
* @desc
*/
public class Main {
public static void main(String[] args) throws Exception {
String filepath ="E:\\all_cach\\11.xls";
InputStream inputStream = new FileInputStream(filepath);
HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
HSSFSheet hssfSheet = workbook.getSheetAt(0);
HSSFRow row = hssfSheet.getRow(0);//Row
for(int i = 0;i<hssfSheet.getLastRowNum();i++){
row = hssfSheet.getRow(i);
for(int j =0;j<row.getLastCellNum();j++){
HSSFCell cell = row.getCell((short)j);//Cell
if(cell!=null){
@SuppressWarnings("deprecation")
String s=getCellContent(cell);//读取单元格String内容
System.out.println(s);
}else{
System.out.println("nullllllll");
}
}
}
}//单元格格式不同 ,需要分开获取内容,数字 字符串,就是设置为一样的也有问题。用String获取
//如 cell.getStringCellValue() 会报这样的错:Cannot get a text value from a numeric cell。
public static String getCellContent(HSSFCell cell ) {
String cellValue = "null";
if (null != cell) {
switch (cell.getCellType()) { // 判断excel单元格内容的格式,并对其进行转换,以便插入数据库
case 0:
cellValue = String.valueOf((int) cell.getNumericCellValue());
break;
case 1:
cellValue = cell.getStringCellValue();
break;
case 2:
cellValue = cell.getNumericCellValue() + "";
// cellValue = String.valueOf(cell.getDateCellValue());
break;
case 3:
cellValue = "";
break;
case 4:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case 5:
cellValue = String.valueOf(cell.getErrorCellValue());
break;
}
} else {
cellValue = "";
}
return cellValue;
}}
java 读取excel HSSFWorkbook方式
最新推荐文章于 2023-08-02 11:09:10 发布