Poi工具类
package com.clouddo.basicdb.common;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PoiUtil {
public static List<String[]> readExcel(MultipartFile file) throws IOException {
return readExcel(file.getInputStream(),file.getOriginalFilename(),1,0);
}
public static List<String[]> readExcel(InputStream file, String fileName, int starRow, int starCell) {
Workbook wb = null;
try {
if (isExcel2007(fileName)) {
wb = new XSSFWorkbook(file);
}
if (isExcel2003(fileName)) {
wb = new HSSFWorkbook(file);
}
} catch (Exception e) {
logger.error("解析excel文档流有误。", e);
} finally {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
List<String[]> list = new ArrayList<>();
Sheet sheet = wb.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
for (int i = starRow; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
int lastCellNum = row.getLastCellNum();
String[] obj = new String[lastCellNum];
for (int j = starCell; j < lastCellNum; j++) {
Cell cell = row.getCell(j);
obj[j] = getMyCellType(cell);
}
list.add(obj);
}
wb.close();
logger.info("读取excel,成功将其转成Object数组");
return list;
} catch (Exception e) {
logger.error("解析excel文档流有误。", e);
return null;
}
}
public static void downLoadExcel(String[] columnNames, String[] keyList, List<?> objList, String filePath, String fileName){
if (objList.size() > 1000000){
List<List<?>> lists = fixedGrouping(objList, 1000000);
for (int i = 0; i < lists.size(); i++) {
downLoadExcelManySheet(columnNames,keyList,lists,filePath,fileName,0);
}
}else {
downLoadExcelSingleSheet(columnNames,keyList,objList,filePath,fileName);
}
}
private static void downLoadExcelManySheet(String[] columnNames, String[] keyList, List<List<?>> objList, String filePath, String fileName,int num) {
Workbook wb = null;
if (isExcel2007(fileName)) {
wb = new SXSSFWorkbook();
}
if (isExcel2003(fileName)) {
wb = new HSSFWorkbook();
}
for (int a = 0; a < objList.size(); a++) {
List<?> objects = objList.get(a);
Sheet sheet = wb.createSheet("sheet" + a);
Row row = sheet.createRow(0);
for (int i = 0; i < keyList.length; i++) {
row.createCell(i).setCellValue(keyList[i]);
}
Object project = null;
for (int i = 0; i < objects.size(); i++) {
Row row1 = sheet.createRow(i+1);
for (int j = 0; j < columnNames.length; j++) {
project = objects.get(i);
row1.createCell(j).setCellValue(getValueByName(columnNames[j],project)+"");
}
}
}
try {
FileOutputStream fileOut = new FileOutputStream(filePath+"\\"+fileName);
wb.write(fileOut);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void downLoadExcelSingleSheet(String[] columnNames, String[] keyList, List<?> objList, String filePath, String fileName) {
Workbook wb = null;
if (isExcel2007(fileName)) {
wb = new SXSSFWorkbook();
}
if (isExcel2003(fileName)) {
wb = new HSSFWorkbook();
}
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
for (int i = 0; i < keyList.length; i++) {
row.createCell(i).setCellValue(keyList[i]);
}
Object project = null;
for (int i = 0; i < objList.size(); i++) {
Row row1 = sheet.createRow(i+1);
for (int j = 0; j < columnNames.length; j++) {
project = objList.get(i);
row1.createCell(j).setCellValue(getValueByName(columnNames[j],project)+"");
}
}
try {
FileOutputStream fileOut = new FileOutputStream(filePath+"\\"+fileName);
wb.write(fileOut);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Object getValueByName(String fieldName, Object obj){
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = obj.getClass().getMethod(getter, new Class[] {
});
Object value = method.invoke(obj, new Object[] {
});
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static String getMyCellType(Cell cell){
String value = "";
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
value=sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue())).toString();
break;
} else {
value = new DecimalFormat("0").format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue() + "";
break;
case Cell.CELL_TYPE_FORMULA:
value = cell.getCellFormula() + "";
break;
case Cell.CELL_TYPE_BLANK:
value = "";
break;
case Cell.CELL_TYPE_ERROR:
value = "非法字符";
break;
default:
value = "未知类型";
break;
}
return value;
}
private static void close(MultipartFile file) {
try {
InputStream inputStream = file.getInputStream();
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
private static void close(InputStream file) {
if (file != null) {
try {
file.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
private static boolean isMobile(String str) {
Pattern p = null;
Matcher m = null;
boolean isMatch = false;
String regex1 = "^[1][3,4,5,7,8][0-9]{9}$";
String regex2 = "^((13[0-9])|(14[579])|(15([0-3,5-9]))|(16[6])|(17[0135678])|(18[0-9]|19[89]))\\d{8}$";
p = Pattern.compile(regex2);
m = p.matcher(str);
isMatch = m.matches();
return isMatch;
}
private static List<List<?>> fixedGrouping(List<?> source, Integer n) {
if (null == source || source.size() == 0 || n <= 0)
return null;
List<List<?>> result = new ArrayList<>();
int remainder = source.size() % n;
int size = (source.size() / n);
for (int i = 0; i < size; i++) {
List<?> subset = null;
subset = source.subList(i * n, (i + 1) * n);
result.add(subset);
}
if (remainder > 0) {
List<?> subset = null;
subset = source.subList(size * n, size * n + remainder);
result.add(subset);
}
return result;
}
private static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
private static String suffix_xls = ".xls";
private static String suffix_xlsx = ".xlsx";
private static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
private static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
private static boolean isCorrectExcel(String filePath) {
if (isExcel2003(filePath) || isExcel2003(filePath)) {
return true;
} else {
return false;
}
}
}