POI导入工具类

扫码查看

前言

导入的通用方法,包括xls、xlsx的取值方法,非空判断方法,空行判断,处理了手机号读取和日期读取格式问题。这几个方法就可以完成简单读取了,有时间我在优化下。

maven依赖

<!-- POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>

导入工具类

package cc.vvxtoys.poi;
import java.math.BigDecimal;
import java.text.SimpleDateFormat; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell; public class ImportExcelUtils {
public static final String EXCEL_2003 = ".xls";
public static final String EXCEL_2007 = ".xlsx"; @SuppressWarnings("static-access")
public String getValue(XSSFCell cell) {
if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue()).trim();
} else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return String.valueOf(sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()))).trim();
}
BigDecimal bd = new BigDecimal(String.valueOf(cell.getNumericCellValue()).trim());
return bd.toPlainString();
} else {
return String.valueOf(cell.getStringCellValue()).trim();
}
} @SuppressWarnings("static-access")
public String getValue(HSSFCell cell) {
if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue()).trim();
} else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return String.valueOf(sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()))).trim();
}
BigDecimal bd = new BigDecimal(String.valueOf(cell.getNumericCellValue()).trim());
return bd.toPlainString();
} else {
return String.valueOf(cell.getStringCellValue()).trim();
}
}
//判断空行
public boolean isBlank(Row row){
for(int i=0;i<row.getLastCellNum();i++){
Cell cell = row.getCell(i);
if(cell!=null&&cell.getCellType()!=cell.CELL_TYPE_BLANK){
return false;
}
}
return true;
}
//非空判断
public boolean isEmpty(Object obj){
if (obj instanceof HSSFCell) {
HSSFCell cell = (HSSFCell) obj;
return getValue(cell) == null || "".equals(getValue(cell));
}
if (obj instanceof XSSFCell) {
XSSFCell cell = (XSSFCell) obj;
return getValue(cell) == null || "".equals(getValue(cell));
}
return obj == null || obj.toString().trim().equals("");
} }
05-07 15:16
查看更多