使用 Apache POI:4.0.0
org.apache.poi
poi
4.0.0
目录
Java使用POI导入Excel文件
前言
一、代码
1.POI导入工具类
2.具体业务使用
总结
前言
巩固下工作中使用的方法,进行记录下,使用 Apache POI导入Excel文件,导入的Excel的工具类以及一些业务代码。
一、代码
1.POI导入工具类
package com.risit.spm.construct.utils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
public class importExcelUtils {
public static void validCellValue(Sheet sheet, Row row, int colNum, String errorHint) {
if ("".equals(getCellValue(sheet, row, colNum - 1))) {
throw new RuntimeException("校验 :第" + (row.getRowNum() + 1) + "行" + colNum + "列" + errorHint + "不能为空");
}
}
public static Workbook getWorkbookByInputStream(InputStream iStream, String fileName) {
Workbook workbook = null;
try {
if (null == fileName) {
return null;
}
if (fileName.endsWith(".xls")) {
workbook = new HSSFWorkbook(iStream);
} else if (fileName.endsWith(".xlsx")) {
workbook = new XSSFWorkbook(iStream);
} else if (fileName.endsWith(".xlsm")) {
workbook = new XSSFWorkbook(iStream);
} else {
throw new IOException("The document type don't support");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (iStream != null) {
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return workbook;
}
public static Sheet getSheetByWorkbook(Workbook workbook, int index) {
Sheet sheet = workbook.getSheetAt(index);
if (null == sheet) {
sheet = workbook.createSheet();
}
sheet.setDefaultRowHeightInPoints(20);//行高
sheet.setDefaultColumnWidth(20);//列宽
return sheet;
}
public static String getCellValue(Sheet sheet, Row row, int column) {
if (sheet == null || row == null) {
return "";
}
return getCellValue(row.getCell(column));
}
public static String getCellValue(Cell cell) {
if (cell == null) {
return "";
}
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
switch (cell.getCellType()) {
case NUMERIC:
Number number = cell.getNumericCellValue();
String numberStr = String.valueOf(number);
if (HSSFDateUtil.isCellDateFormatted(cell)){
return sdf.format(cell.getDateCellValue());
}
if (numberStr.endsWith(".0")) {
numberStr = numberStr.replace(".0", "");//取整数
}
if (numberStr.indexOf("E") >= 0) {
numberStr = new DecimalFormat("#").format(number);//取整数
}
return numberStr;
case STRING:
return cell.getStringCellValue().trim();
case FORMULA://公式
return "";
case BLANK:
return "";
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
default:
break;
}
return "";
}
public static boolean isBlankRow(Row row) {
if (row == null) {
return true;
}
Iterator| iter = row.cellIterator();
while (iter.hasNext()) {
Cell cell = iter.next();
if (cell == null) {
continue;
}
String value = getCellValue(cell);
if (!isNULLOrBlank(value)) {
return false;
}
}
return true;
}
public static boolean isNULLOrBlank(Object obj) {
if (obj != null && !"".equals(obj.toString())) {
return false;
}
return true;
}
}
|
2.具体业务使用
1.POI导入工具类
package com.risit.spm.construct.utils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
public class importExcelUtils {
public static void validCellValue(Sheet sheet, Row row, int colNum, String errorHint) {
if ("".equals(getCellValue(sheet, row, colNum - 1))) {
throw new RuntimeException("校验 :第" + (row.getRowNum() + 1) + "行" + colNum + "列" + errorHint + "不能为空");
}
}
public static Workbook getWorkbookByInputStream(InputStream iStream, String fileName) {
Workbook workbook = null;
try {
if (null == fileName) {
return null;
}
if (fileName.endsWith(".xls")) {
workbook = new HSSFWorkbook(iStream);
} else if (fileName.endsWith(".xlsx")) {
workbook = new XSSFWorkbook(iStream);
} else if (fileName.endsWith(".xlsm")) {
workbook = new XSSFWorkbook(iStream);
} else {
throw new IOException("The document type don't support");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (iStream != null) {
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return workbook;
}
public static Sheet getSheetByWorkbook(Workbook workbook, int index) {
Sheet sheet = workbook.getSheetAt(index);
if (null == sheet) {
sheet = workbook.createSheet();
}
sheet.setDefaultRowHeightInPoints(20);//行高
sheet.setDefaultColumnWidth(20);//列宽
return sheet;
}
public static String getCellValue(Sheet sheet, Row row, int column) {
if (sheet == null || row == null) {
return "";
}
return getCellValue(row.getCell(column));
}
public static String getCellValue(Cell cell) {
if (cell == null) {
return "";
}
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
switch (cell.getCellType()) {
case NUMERIC:
Number number = cell.getNumericCellValue();
String numberStr = String.valueOf(number);
if (HSSFDateUtil.isCellDateFormatted(cell)){
return sdf.format(cell.getDateCellValue());
}
if (numberStr.endsWith(".0")) {
numberStr = numberStr.replace(".0", "");//取整数
}
if (numberStr.indexOf("E") >= 0) {
numberStr = new DecimalFormat("#").format(number);//取整数
}
return numberStr;
case STRING:
return cell.getStringCellValue().trim();
case FORMULA://公式
return "";
case BLANK:
return "";
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
default:
break;
}
return "";
}
public static boolean isBlankRow(Row row) {
if (row == null) {
return true;
}
Iterator| iter = row.cellIterator();
while (iter.hasNext()) {
Cell cell = iter.next();
if (cell == null) {
continue;
}
String value = getCellValue(cell);
if (!isNULLOrBlank(value)) {
return false;
}
}
return true;
}
public static boolean isNULLOrBlank(Object obj) {
if (obj != null && !"".equals(obj.toString())) {
return false;
}
return true;
}
}
|
2.具体业务使用
代码如下(示例):
public void importExcel(MultipartFile excelFile) {
int rowNum = 0;//已取值的行数
int colNum = 0;//列号
int realRowCount = 0;//真正有数据的行数
//得到工作空间
Workbook workbook = null;
try {
workbook = importExcelUtils.getWorkbookByInputStream(excelFile.getInputStream(), excelFile.getOriginalFilename());
} catch (IOException e) {
e.printStackTrace();
}
//得到工作表
Sheet sheet = importExcelUtils.getSheetByWorkbook(workbook, 0);
//根据需要是否加条数限制
if (sheet.getRow(1000) != null) {
throw new RuntimeException("系统已限制单批次导入必须小于或等于1000笔!");
}
//获取行数
realRowCount = sheet.getPhysicalNumberOfRows();
//需要添加的表,Project表实体类
List list = new ArrayList<>();
Project p = new Project();
//处理表格数据
for (Row row : sheet) {
if (realRowCount == rowNum) {
break;
}
if (importExcelUtils.isBlankRow(row)) {//空行跳过
continue;
}
if (row.getRowNum() == -1) {
continue;
} else {
if (row.getRowNum() == 0) {//第一行表头跳过
continue;
}
}
rowNum++;
colNum = 1;
//验证Excel文件字段,这里根据表格内名称
importExcelUtils.validCellValue(sheet, row, colNum, "名称");
p.setProjectName(importExcelUtils.getCellValue(sheet, row, colNum - 1));
//列号需要自加获取
importExcelUtils.validCellValue(sheet, row, ++colNum, "地址");
p.setAddress(importExcelUtils.getCellValue(sheet, row, colNum - 1));
//省略重复表格列名数据处理~
list.add(p);
}
System.out.println("导入的项目数据==========>" + list.get(0));
//省略添加到数据库表中代码
}
引包省略,简单记录而已。
具体业务代码根据自己的来处理。
总结
本文仅仅简单记录对POI导入Excel的使用,处理数据方法。



