ExcelUtils.java
import org.apache.poi.ss.usermodel.Workbook;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.logging.Logger;
public class ExcelUtils {
private static Logger logger = Logger.getLogger(ExcelUtils.class.getName());
private ExcelUtils() {
}
static ExcelDataChecker excelDataChecker = new ExcelDataChecker();
public static List<HashMap<String, Object>> parseSingleExcelToMap(@NotNull File excelFile) {
return excelDataChecker.parseSingleExcelToMap(excelFile);
}
public static List<List<HashMap<String, Object>>> parseComplexExcel(@NotNull File excelFile) {
return excelDataChecker.parseComplexExcel(excelFile);
}
public static <T> List<T> readExcelToBean(@NotNull File excelFile, @NotNull Class<T> tClass) {
return excelDataChecker.readExcelToBean(excelFile, tClass);
}
public static <T> List<T> excelToBean(@NotNull File file, @NotNull Class<T> tClass) {
return excelDataChecker.excelToBean(file, tClass);
}
public static void exportExcelToDisks(@NotNull List<LinkedHashMap<String, Object>> dataVOList, @NotNull String exportFilePath, @NotNull String excelName) {
excelDataChecker.exportExcelToDisks(dataVOList, exportFilePath, excelName);
}
public static <T>void exportBeanExcelToDisks(@NotNull List<T> dataVOList, @NotNull String exportFilePath, @NotNull String excelName) {
excelDataChecker.exportBeanExcelToDisks(dataVOList, exportFilePath, excelName);
}
public static void mapExportExcelToResponse(@NotNull HttpServletResponse response, @NotNull String excelName, @NotNull List<LinkedHashMap<String, Object>> dataVOList) {
try (Workbook workbook = excelDataChecker.mapExportData(dataVOList, "",excelName);) {
putTogetherData(response, workbook, excelName);
} catch (Exception e) {
logger.warning("写入Excel过程出错!错误原因:" + e.getMessage());
}
}
public static <T> void beanExportExcelToResponse(@NotNull HttpServletResponse response, @NotNull String excelName, @NotNull List<T> dataVOList) {
try (Workbook workbook = excelDataChecker.beanExportData(dataVOList,"", excelName)) {
putTogetherData(response, workbook, excelName);
} catch (Exception e) {
logger.warning("写入Excel过程出错!错误原因:" + e.getMessage());
}
}
private static void putTogetherData(HttpServletResponse response, Workbook workbook, String excelName) throws IOException {
OutputStream out = null;
if (null != workbook) {
excelName = new String(excelName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
response.setHeader("Content-Disposition", "attachment;filename=" + excelName);
response.setContentType("application/x-download");
response.setCharacterEncoding("UTF-8");
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
response.flushBuffer();
out = response.getOutputStream();
workbook.write(out);
out.flush();
}
}
}
ExcelDataChecker.java
import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.logging.Logger;
public class ExcelDataChecker {
private Logger logger = Logger.getLogger(ExcelDataChecker.class.getName());
ExcelDataChecker() {
}
public List<HashMap<String, Object>> parseSingleExcelToMap(File excelFile) {
List<HashMap<String, Object>> data = new ArrayList<>();
if (filrTypeCheck(excelFile)) return new ArrayList<>();
try (FileInputStream inputStream = new FileInputStream(excelFile);
Workbook workbook = WorkbookFactory.create(inputStream)) {
data = singleSheetCheck(workbook, (byte) 0);
if (!EmptyChecker.isEmpty(data)) return data;
} catch (Exception e) {
logger.warning("解析Excel失败,文件名:" + excelFile.getName() + " 错误信息:" + e.getMessage());
return new ArrayList<>();
}
return data;
}
private boolean filrTypeCheck(File excelFile) {
String fileName = excelFile.getName();
if (EmptyChecker.isEmpty(fileName) || fileName.lastIndexOf('.') < 0 || !excelFile.exists()) {
logger.warning("指定的Excel文件不存在或者存在异常!");
return true;
}
return false;
}
public List<List<HashMap<String, Object>>> parseComplexExcel(File excelFile) {
List<List<HashMap<String, Object>>> listData = new ArrayList<>();
String fileName = excelFile.getName();
if (filrTypeCheck(excelFile)) return new ArrayList<>();
try (FileInputStream inputStream = new FileInputStream(excelFile);
Workbook workbook = WorkbookFactory.create(inputStream)) {
for (byte sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
List<HashMap<String, Object>> data = singleSheetCheck(workbook, sheetNum);
if (!EmptyChecker.isEmpty(data))
listData.add(data);
}
} catch (Exception e) {
logger.warning("解析Excel失败,文件名:" + fileName + " 错误信息:" + e.getMessage());
return new ArrayList<>();
}
return listData;
}
private List<HashMap<String, Object>> singleSheetCheck(Workbook workbook, byte sheetNum) {
List<HashMap<String, Object>> list = new ArrayList<>();
Sheet sheet = workbook.getSheetAt(sheetNum);
int firstRowNum = sheet.getFirstRowNum();
Row firstRow = sheet.getRow(firstRowNum);
if (EmptyChecker.isEmpty(firstRow)) {
logger.warning("解析Excel失败,在第一行没有读取到任何数据!");
}
int rowStart = firstRowNum + 1;
int rowEnd = sheet.getPhysicalNumberOfRows();
for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
HashMap<String, Object> rowsData = new HashMap<>();
Row row = sheet.getRow(rowNum);
if (null == row) {
continue;
}
for (int col = 0; col < sheet.getRow(0).getPhysicalNumberOfCells(); col++) {
Cell cell = row.getCell(col);
String cellValue = convertCellValueToString(cell);
rowsData.put(sheet.getRow(0).getCell(col).getStringCellValue(), cellValue);
}
list.add(rowsData);
}
return list;
}
private String convertCellValueToString(Cell cell) {
if (cell == null) {
return null;
}
String returnValue = null;
switch (cell.getCellType()) {
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
Date tempValue = cell.getDateCellValue();
returnValue = dateCheck(tempValue);
} else {
Object inputValue = null;
Long longVal = Math.round(cell.getNumericCellValue());
Double doubleVal = cell.getNumericCellValue();
if (Double.parseDouble(longVal + ".0") == doubleVal) {
inputValue = longVal;
} else {
inputValue = doubleVal;
}
DecimalFormat df = new DecimalFormat("#.####");
return String.valueOf(df.format(inputValue));
}
break;
case STRING:
returnValue = cell.getStringCellValue();
break;
case BOOLEAN:
Boolean booleanValue = cell.getBooleanCellValue();
returnValue = booleanValue.toString();
break;
case BLANK:
break;
case FORMULA:
returnValue = cell.getCellFormula();
break;
case ERROR:
break;
default:
break;
}
return returnValue;
}
public Workbook mapExportData(List<LinkedHashMap<String, Object>> dataList, String exportFilePath, String fileName) {
try {
Workbook workbook = getWorkbook(exportFilePath, fileName);
HashMap<String, Object> rowMap = dataList.get(0);
List<String> mapKeys = new ArrayList<>(rowMap.keySet());
Sheet sheet = buildDataSheet(workbook, mapKeys);
int rowNum = 1;
for (int i = 0; i < dataList.size(); i++) {
HashMap<String, Object> data = dataList.get(i);
if (EmptyChecker.isEmpty(dataList.get(i))) {
continue;
}
Row row = sheet.createRow(rowNum++);
convertDataToRow(data, row);
}
return workbook;
} catch (Exception e) {
logger.warning("excel生成过程中发生异常 ,{}" + e.getMessage());
return null;
}
}
public <T> Workbook beanExportData(List<T> dataList, String exportFilePath, String fileName) {
if (EmptyChecker.isEmpty(dataList)) {
throw new NullPointerException("The data list is empty");
}
try {
Workbook workbook = getWorkbook(exportFilePath, fileName);
Class<T> tClassOne = (Class<T>) (dataList.get(0).getClass());
Field[] fieldsOne = tClassOne.getDeclaredFields();
Sheet sheet = buildDataSheet(workbook, fieldsOne);
for (int i = 0; i < dataList.size(); i++) {
if (EmptyChecker.isEmpty(dataList.get(i))) {
continue;
}
Class<T> tClass = (Class<T>) (dataList.get(i).getClass());
Field[] fields = tClass.getDeclaredFields();
Row row = sheet.createRow(i + 1);
for (int j = 0; j < fields.length; j++) {
Field field = fields[j];
String beanValue = getBeanValue(dataList.get(i), field);
if (EmptyChecker.isEmpty(beanValue)) {
continue;
}
Cell cell = row.createCell(j);
cell.setCellValue(beanValue);
}
}
return workbook;
} catch (Exception e) {
logger.warning("excel生成过程中发生异常 ,{}" + e.getMessage());
return null;
}
}
private Sheet buildDataSheet(Workbook workbook, Field[] fields) {
Sheet sheet = workbook.createSheet();
for (int i = 0; i < fields.length; i++) {
sheet.setColumnWidth(i, 4000);
}
sheet.setDefaultRowHeight((short) 400);
CellStyle cellStyle = buildHeadCellStyle(sheet.getWorkbook());
Row head = sheet.createRow(0);
for (int i = 0; i < fields.length; i++) {
Cell cell = head.createCell(i);
Field field = fields[i];
field.setAccessible(true);
String name = field.getName();
cell.setCellValue(name);
cell.setCellStyle(cellStyle);
}
return sheet;
}
private Sheet buildDataSheet(Workbook workbook, List<String> keySet) {
Sheet sheet = workbook.createSheet();
for (int i = 0; i < keySet.size(); i++) {
sheet.setColumnWidth(i, 4000);
}
sheet.setDefaultRowHeight((short) 400);
CellStyle cellStyle = buildHeadCellStyle(sheet.getWorkbook());
Row head = sheet.createRow(0);
for (int i = 0; i < keySet.size(); i++) {
Cell cell = head.createCell(i);
cell.setCellValue(keySet.get(i));
cell.setCellStyle(cellStyle);
}
return sheet;
}
private CellStyle buildHeadCellStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderTop(BorderStyle.THIN);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);
return style;
}
private void convertDataToRow(HashMap<String, Object> data, Row row) {
Cell cell;
int i = 0;
final Set<String> keys = data.keySet();
for (String key : keys) {
cell = row.createCell(i);
cell.setCellValue(EmptyChecker.isEmpty(data.get(key)) ? "" : dateCheck(data.get(key)));
i++;
}
}
private String dateCheck(Object obj) {
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return (obj instanceof Date || obj instanceof LocalDate) ? simpleFormat.format(obj) : String.valueOf(obj);
}
public void exportExcelToDisks(List<LinkedHashMap<String, Object>> dataVOList, String exportFilePath, String excelName) {
try (Workbook workbook = mapExportData(dataVOList, exportFilePath, excelName);
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(exportFilePath + excelName),1024)) {
workbook.write(outputStream);
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public <T> void exportBeanExcelToDisks(List<T> data, String exportFilePath, String excelName) {
try (Workbook workbook = beanExportData(data, exportFilePath, excelName);
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(exportFilePath + excelName),1024)) {
workbook.write(outputStream);
outputStream.flush();
} catch (Exception e) {
logger.warning("输出Excel时发生错误,错误原因:" + e.getMessage());
}
}
public <T> List<T> readExcelToBean(File file, Class<T> tClass) {
List<T> listBean = new ArrayList<>();
try (FileInputStream inputStream = new FileInputStream(file)) {
List<List<String>> list = readExcel(inputStream);
Field[] fields = tClass.getDeclaredFields();
T uBean = null;
for (int i = 1; i < list.size(); i++) {
uBean = (T) tClass.newInstance();
List<String> listStr = list.get(i);
for (int j = 0; j < listStr.size(); j++) {
if (j >= fields.length) {
break;
}
Field field = fields[j];
String dataString = listStr.get(j);
field.setAccessible(true);
if (EmptyChecker.notEmpty(dataString)) {
Class<?> type = field.getType();
dataTypeCheck(type, field, uBean, dataString);
}
}
listBean.add(uBean);
}
} catch (Exception e) {
logger.warning("excel读取过程中发生异常 ,{}" + e.getMessage());
}
return listBean;
}
public List<List<String>> readExcel(InputStream is) throws IOException {
List<List<String>> dataLst = new ArrayList<>();
try (Workbook wb = WorkbookFactory.create(is)) {
Sheet sheet = wb.getSheetAt(0);
int totalRows = sheet.getPhysicalNumberOfRows();
int totalCells = 0;
if (totalRows >= 1 && sheet.getRow(0) != null) {
totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
for (int r = 0; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null)
continue;
List<String> rowLst = new ArrayList<>();
for (int c = 0; c < totalCells; c++) {
Cell cell = row.getCell(c);
String cellValue = "";
if (null != cell) {
HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
cellValue = hSSFDataFormatter.formatCellValue(cell);
}
rowLst.add(cellValue);
}
dataLst.add(rowLst);
}
} catch (Exception e) {
logger.warning("excel读取过程中发生异常 ,{}" + e.getMessage());
}
return dataLst;
}
public <T> List<T> excelToBean(File file, Class<T> tClass) {
List<T> listBean = new ArrayList<>();
try (FileInputStream inputStream = new FileInputStream(file)) {
List<HashMap<String, Object>> listData = parseSingleExcelToMap(file);
Field[] fields = tClass.getDeclaredFields();
T uBean = null;
for (int i = 0; i < listData.size(); i++) {
uBean = (T) tClass.newInstance();
HashMap<String, Object> map = listData.get(i);
for (Map.Entry<String, Object> entry : map.entrySet()) {
for (int k = 0; k < fields.length; k++) {
Field field = fields[k];
field.setAccessible(true);
String dataStr = entry.getValue().toString();
Class<?> type = field.getType();
String name = field.getName();
if (entry.getKey().equals(name)) {
dataTypeCheck(type, field, uBean, dataStr);
}
}
}
listBean.add(uBean);
}
} catch (Exception e) {
logger.warning("excel转换bean发生异常 ,{}" + e.getMessage());
}
return listBean;
}
private <T> void dataTypeCheck(Class<?> type, Field field, T uBean, String dataStr) {
try {
if (type == String.class) {
field.set(uBean, dataStr);
}
if (type == Integer.class || type == int.class) {
field.set(uBean, Integer.parseInt(dataStr));
}
if (type == Double.class || type == double.class) {
field.set(uBean, Double.parseDouble(dataStr));
}
if (type == Float.class || type == float.class) {
field.set(uBean, Float.parseFloat(dataStr));
}
if (type == Long.class || type == long.class) {
field.set(uBean, Long.parseLong(dataStr));
}
if (type == Boolean.class || type == boolean.class) {
field.set(uBean, Boolean.parseBoolean(dataStr));
}
if (type == Short.class || type == short.class) {
field.set(uBean, Short.parseShort(dataStr));
}
if (type == Byte.class || type == byte.class) {
field.set(uBean, Byte.parseByte(dataStr));
}
if (type == Character.class || type == char.class) {
field.set(uBean, dataStr.charAt(0));
}
if (type == Date.class || type == LocalDate.class) {
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
field.set(uBean, simpleFormat.parse(String.valueOf(dataStr)));
}
} catch (Exception e) {
logger.warning("反射泛型处理发生异常 ,{}" + e.getMessage());
}
}
private String getBeanValue(Object obj, Field field) {
try {
field.setAccessible(true);
String name = field.getName();
name = name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase());
Method m = obj.getClass().getMethod("get" + name);
return dateCheck(m.invoke(obj));
} catch (Exception e) {
logger.warning("反射泛型处理发生异常 ,{}" + e.getMessage());
return null;
}
}
private Workbook getWorkbook(String exportFilePath, String fileName) throws IllegalAccessException {
if (EmptyChecker.isEmpty(fileName) || fileName.lastIndexOf('.') < 0) {
logger.warning("指定的Excel文件不存在或者存在异常!");
throw new IllegalStateException("指定文件类型异常");
}
Workbook workbook = null;
if (fileName.contains(".xlsx")) {
workbook = new SXSSFWorkbook(getXSSFWorkbook(exportFilePath + fileName), 100);
} else if (fileName.contains(".xls")) {
workbook = new HSSFWorkbook();
} else {
throw new IllegalAccessException("指定excel类型异常");
}
return workbook;
}
public XSSFWorkbook getXSSFWorkbook(String filePath) {
XSSFWorkbook workbook = null;
BufferedOutputStream outputStream = null;
try {
File fileXlsxPath = new File(filePath);
outputStream = new BufferedOutputStream(new FileOutputStream(fileXlsxPath));
workbook = new XSSFWorkbook();
workbook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
}
return workbook;
}
}
EmptyChecker.java
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
public class EmptyChecker {
private EmptyChecker() {
}
public static boolean isEmpty(Object obj) {
if (obj == null || "null".equals(obj.toString()) || "".equals(obj.toString())) {
return true;
}
if (obj instanceof String) {
return ((String) obj).trim().length() == 0;
}
if (obj instanceof Collection) {
return ((Collection) obj).isEmpty();
}
if (obj instanceof Map) {
return ((Map) obj).isEmpty();
}
return false;
}
public static boolean notEmpty(Object obj) {
return !isEmpty(obj);
}
public static boolean isEmpty(Object[] array) {
return array == null || array.length == 0;
}
public static boolean notEmpty(Object[] array) {
return !isEmpty(array);
}
public static boolean isAnyOneEmpty(Object... obj) {
for (int i = 0; i < obj.length; i++) {
boolean empty = isEmpty(obj[i]);
if (empty) {
return true;
}
}
return false;
}
public static boolean isAllEmpty(Object... obj) {
for (int i = 0; i < obj.length; i++) {
boolean temp = notEmpty(obj[i]);
if (temp) {
return false;
}
}
return true;
}
public static <T> boolean beanIsEmpty(T t) {
if (notEmpty(t)) {
Field[] fields = t.getClass().getDeclaredFields();
for (Field obj : fields) {
if (isEmpty(getBeanValue(t, obj))) {
return true;
}
}
return false;
}
return true;
}
public static <T> boolean beanIsAllEmpty(T t) {
if (notEmpty(t)) {
Field[] fields = t.getClass().getDeclaredFields();
for (Field obj : fields) {
if (notEmpty(getBeanValue(t, obj))) {
return false;
}
}
}
return true;
}
private static String getBeanValue(Object obj, Field field) {
try {
field.setAccessible(true);
String name = field.getName();
name = name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase());
Method method = obj.getClass().getMethod("get" + name);
return dateCheck(method.invoke(obj));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static String dateCheck(Object obj) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return (obj instanceof Date || obj instanceof LocalDate) ? simpleDateFormat.format(obj) : String.valueOf(obj);
}
}
依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>