import com.beust.jcommander.internal.Lists;
import com.bootplant.common.core.annotation.Excel;
import com.bootplant.common.core.annotation.Excel.ColumnType;
import com.bootplant.common.core.annotation.Excel.Type;
import com.bootplant.common.core.annotation.Excels;
import com.bootplant.common.core.model.AreaVo;
import com.bootplant.common.core.text.Convert;
import com.bootplant.common.core.utils.AreaUtils;
import com.bootplant.common.core.utils.DateUtils;
import com.bootplant.common.core.utils.DictUtils;
import com.bootplant.common.core.utils.StringUtils;
import com.bootplant.common.core.utils.file.FileTypeUtils;
import com.bootplant.common.core.utils.file.ImageUtils;
import com.bootplant.common.core.utils.reflect.ReflectUtils;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;
public class ExcelUtil<T> {
private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
public static final int sheetSize = 65536;
private String sheetName;
private Type type;
private Workbook wb;
private Sheet sheet;
private Map<String, CellStyle> styles;
private List<T> list;
private List<Object[]> fields;
private int rownum;
private String title;
private short maxHeight;
private Map<Integer, Double> statistics = new HashMap<Integer, Double>();
private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");
public Class<T> clazz;
private boolean hasExportTemplate = false;
public ExcelUtil(Class<T> clazz) {
this.clazz = clazz;
}
public void init(List<T> list, String sheetName, String title, Type type) {
if (list == null) {
list = new ArrayList<T>();
}
this.list = list;
this.sheetName = sheetName;
this.type = type;
this.title = title;
createExcelField();
createWorkbook();
createTitle();
}
public void createTitle() {
if (StringUtils.isNotEmpty(title)) {
Row titleRow = sheet.createRow(rownum == 0 ? rownum++ : 0);
titleRow.setHeightInPoints(30);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellStyle(styles.get("title"));
titleCell.setCellValue(title);
sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(),
this.fields.size() - 1));
}
}
public List<T> importExcel(InputStream is) throws Exception {
return importExcel(is, 0);
}
public List<T> importExcel(InputStream is, int titleNum) throws Exception {
return importExcel(StringUtils.EMPTY, is, titleNum);
}
public List<T> importExcel(String sheetName, InputStream is, int titleNum) throws Exception {
this.type = Type.IMPORT;
this.wb = WorkbookFactory.create(is);
List<T> list = new ArrayList<T>();
Sheet sheet = StringUtils.isNotEmpty(sheetName) ? wb.getSheet(sheetName) : wb.getSheetAt(0);
if (sheet == null) {
throw new IOException("文件sheet不存在");
}
int rows = sheet.getLastRowNum();
if (rows > 0) {
Map<String, Integer> cellMap = new HashMap<String, Integer>();
Row heard = sheet.getRow(titleNum);
for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) {
Cell cell = heard.getCell(i);
if (StringUtils.isNotNull(cell)) {
String value = this.getCellValue(heard, i).toString();
cellMap.put(value, i);
} else {
cellMap.put(null, i);
}
}
List<Object[]> fields = this.getFields();
Map<Integer, Object[]> fieldsMap = new HashMap<Integer, Object[]>();
for (Object[] objects : fields) {
Excel attr = (Excel) objects[1];
Integer column = cellMap.get(attr.name());
if (column != null) {
fieldsMap.put(column, objects);
}
}
for (int i = titleNum + 1; i <= rows; i++) {
Row row = sheet.getRow(i);
if (isRowEmpty(row)) {
continue;
}
T entity = null;
for (Map.Entry<Integer, Object[]> entry : fieldsMap.entrySet()) {
Object val = this.getCellValue(row, entry.getKey());
entity = (entity == null ? clazz.newInstance() : entity);
Field field = (Field) entry.getValue()[0];
Excel attr = (Excel) entry.getValue()[1];
Class<?> fieldType = field.getType();
if (String.class == fieldType) {
String s = Convert.toStr(val);
if (StringUtils.endsWith(s, ".0")) {
val = StringUtils.substringBefore(s, ".0");
} else {
String dateFormat = field.getAnnotation(Excel.class).dateFormat();
if (StringUtils.isNotEmpty(dateFormat)) {
val = DateUtils.parseDateToStr(dateFormat, (Date) val);
} else {
val = Convert.toStr(val);
}
}
} else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val))) {
val = Convert.toInt(val);
} else if (Long.TYPE == fieldType || Long.class == fieldType) {
val = Convert.toLong(val);
} else if (Double.TYPE == fieldType || Double.class == fieldType) {
val = Convert.toDouble(val);
} else if (Float.TYPE == fieldType || Float.class == fieldType) {
val = Convert.toFloat(val);
} else if (BigDecimal.class == fieldType) {
val = Convert.toBigDecimal(val);
} else if (Date.class == fieldType) {
if (val instanceof String) {
val = DateUtils.parseDate(val);
} else if (val instanceof Double) {
val = DateUtil.getJavaDate((Double) val);
}
} else if (Boolean.TYPE == fieldType || Boolean.class == fieldType) {
val = Convert.toBool(val, false);
}
if (StringUtils.isNotNull(fieldType)) {
String propertyName = field.getName();
if (StringUtils.isNotEmpty(attr.targetAttr())) {
propertyName = field.getName() + "." + attr.targetAttr();
} else if (StringUtils.isNotEmpty(attr.readConverterExp())) {
val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
} else if (StringUtils.isNotEmpty(attr.dictType())) {
val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator());
} else if (!attr.handler().equals(ExcelHandlerAdapter.class)) {
val = dataFormatHandlerAdapter(val, attr);
}
ReflectUtils.invokeSetter(entity, propertyName, val);
}
}
list.add(entity);
}
}
return list;
}
public void exportExcel(HttpServletResponse response, List<T> list, String sheetName) {
exportExcel(response, list, sheetName, StringUtils.EMPTY);
}
public void exportExcel(HttpServletResponse response, List<T> list, String sheetName, String title) {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
this.init(list, sheetName, title, Type.EXPORT);
exportExcel(response);
}
public void importTemplateExcel(HttpServletResponse response, String sheetName) {
importTemplateExcel(response, sheetName, StringUtils.EMPTY);
}
public void importTemplateExcel(HttpServletResponse response, String sheetName, String title) {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
this.hasExportTemplate = true;
this.init(null, sheetName, title, Type.IMPORT);
exportExcel(response);
}
public void exportExcel(HttpServletResponse response) {
try {
writeSheet();
wb.write(response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
log.error("导出Excel异常{}", e.getMessage());
} finally {
IOUtils.closeQuietly(wb);
}
}
public void writeSheet() {
int sheetNo = Math.max(1, (int) Math.ceil(list.size() * 1.0 / sheetSize));
for (int index = 0; index < sheetNo; index++) {
createSheet(sheetNo, index);
Row row = sheet.createRow(rownum);
int column = 0;
for (Object[] os : fields) {
Excel excel = (Excel) os[1];
this.createCell(excel, row, column++);
}
if (Type.EXPORT.equals(type)) {
fillExcelData(index, row);
addStatisticsRow();
}
}
}
public void fillExcelData(int index, Row row) {
int startNo = index * sheetSize;
int endNo = Math.min(startNo + sheetSize, list.size());
for (int i = startNo; i < endNo; i++) {
row = sheet.createRow(i + 1 + rownum - startNo);
T vo = (T) list.get(i);
int column = 0;
for (Object[] os : fields) {
Field field = (Field) os[0];
Excel excel = (Excel) os[1];
this.addCell(excel, row, vo, field, column++);
}
}
}
private Map<String, CellStyle> createStyles(Workbook wb) {
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
CellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
Font titleFont = wb.createFont();
titleFont.setFontName("Arial");
titleFont.setFontHeightInPoints((short) 16);
titleFont.setBold(true);
style.setFont(titleFont);
styles.put("title", style);
style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderTop(BorderStyle.THIN);
style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
Font dataFont = wb.createFont();
dataFont.setFontName("Arial");
dataFont.setFontHeightInPoints((short) 10);
style.setFont(dataFont);
styles.put("data", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
Font headerFont = wb.createFont();
headerFont.setFontName("Arial");
headerFont.setFontHeightInPoints((short) 10);
headerFont.setBold(true);
headerFont.setColor(IndexedColors.WHITE.getIndex());
style.setFont(headerFont);
styles.put("header", style);
style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
Font totalFont = wb.createFont();
totalFont.setFontName("Arial");
totalFont.setFontHeightInPoints((short) 10);
style.setFont(totalFont);
styles.put("total", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(HorizontalAlignment.LEFT);
styles.put("data1", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(HorizontalAlignment.CENTER);
styles.put("data2", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(HorizontalAlignment.RIGHT);
styles.put("data3", style);
return styles;
}
public Cell createCell(Excel attr, Row row, int column) {
Cell cell = row.createCell(column);
cell.setCellValue(attr.name());
setDataValidation(attr, row, column);
cell.setCellStyle(styles.get("header"));
return cell;
}
public void setCellVo(Object value, Excel attr, Cell cell) {
if (ColumnType.STRING == attr.cellType()) {
cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix());
} else if (ColumnType.NUMERIC == attr.cellType()) {
if (StringUtils.isNotNull(value)) {
cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
}
} else if (ColumnType.IMAGE == attr.cellType()) {
ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
String imagePath = Convert.toStr(value);
if (StringUtils.isNotEmpty(imagePath)) {
byte[] data = ImageUtils.getImage(imagePath);
getDrawingPatriarch(cell.getSheet()).createPicture(anchor,
cell.getSheet().getWorkbook().addPicture(data, getImageType(data)));
}
}
}
public static Drawing<?> getDrawingPatriarch(Sheet sheet) {
if (sheet.getDrawingPatriarch() == null) {
sheet.createDrawingPatriarch();
}
return sheet.getDrawingPatriarch();
}
public int getImageType(byte[] value) {
String type = FileTypeUtils.getFileExtendName(value);
if ("JPG".equalsIgnoreCase(type)) {
return Workbook.PICTURE_TYPE_JPEG;
} else if ("PNG".equalsIgnoreCase(type)) {
return Workbook.PICTURE_TYPE_PNG;
}
return Workbook.PICTURE_TYPE_JPEG;
}
public void setDataValidation(Excel attr, Row row, int column) {
if (attr.name().indexOf("注:") >= 0) {
sheet.setColumnWidth(column, 6000);
} else {
sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
}
if (StringUtils.isNotEmpty(attr.prompt())) {
setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);
}
if (hasExportTemplate && (!StringUtils.isEmpty(attr.readConverterExp()) || !StringUtils.isEmpty(attr.dictType()))) {
setXSSFValidation(sheet, fillValidation(attr), 1, 65535, column, column);
}
if (hasExportTemplate && attr.AreaType()) {
Cascade(sheet, 1, 1000, column, column);
}
}
private String[] fillValidation(Excel attr) {
List<String> result = new ArrayList<>();
if (!StringUtils.isEmpty(attr.readConverterExp())) {
String[] converterExp = attr.readConverterExp().split(",");
for (String str : converterExp) {
String[] split = str.split("=");
result.add(split[1]);
}
}
if (CollectionUtils.isEmpty(result) && !StringUtils.isEmpty(attr.dictType())) {
List<String> dictLabelList = DictUtils.getDictLabelList(attr.dictType());
if (!CollectionUtils.isEmpty(dictLabelList)) {
result.addAll(dictLabelList);
}
}
return result.toArray(new String[0]);
}
public Cell addCell(Excel attr, Row row, T vo, Field field, int column) {
Cell cell = null;
try {
row.setHeight(maxHeight);
if (attr.isExport()) {
cell = row.createCell(column);
int align = attr.align().value();
cell.setCellStyle(styles.get("data" + (align >= 1 && align <= 3 ? align : "")));
Object value = getTargetValue(vo, field, attr);
String dateFormat = attr.dateFormat();
String readConverterExp = attr.readConverterExp();
String separator = attr.separator();
String dictType = attr.dictType();
if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value)) {
cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value));
} else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value)) {
cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
} else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value)) {
cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator));
} else if (value instanceof BigDecimal && -1 != attr.scale()) {
cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString());
} else if (!attr.handler().equals(ExcelHandlerAdapter.class)) {
cell.setCellValue(dataFormatHandlerAdapter(value, attr));
} else {
setCellVo(value, attr, cell);
}
addStatisticsData(column, Convert.toStr(value), attr);
}
} catch (Exception e) {
log.error("导出Excel失败{}", e);
}
return cell;
}
public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,
int firstCol, int endCol) {
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
DataValidation dataValidation = helper.createValidation(constraint, regions);
dataValidation.createPromptBox(promptTitle, promptContent);
dataValidation.setShowPromptBox(true);
sheet.addValidationData(dataValidation);
}
public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) {
Sheet hiddenSheet = wb.createSheet("hiddenSelect" + firstCol);
Cell cell = null;
for (int i = 0; i < textlist.length; i++) {
Row ro = hiddenSheet.createRow(i);
cell = ro.createCell(0);
cell.setCellValue(textlist[i]);
}
Name nameCell = wb.createName();
nameCell.setNameName(hiddenSheet.getSheetName());
nameCell.setRefersToFormula(hiddenSheet.getSheetName() + "!$A$1:$A$" + textlist.length);
wb.setSheetHidden(wb.getSheetIndex(hiddenSheet), true);
CellRangeAddressList addressList = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
DataValidationConstraint constraint = null;
DataValidation validation = null;
DataValidationHelper helper = sheet.getDataValidationHelper();
if (sheet instanceof XSSFSheet || sheet instanceof SXSSFSheet) {
constraint = helper.createFormulaListConstraint(hiddenSheet.getSheetName());
validation = helper.createValidation(constraint, addressList);
} else {
constraint = DVConstraint.createFormulaListConstraint(hiddenSheet.getSheetName());
validation = new HSSFDataValidation(addressList, constraint);
}
if (validation instanceof XSSFDataValidation) {
validation.setSuppressDropDownArrow(true);
validation.setShowErrorBox(true);
} else {
validation.setSuppressDropDownArrow(false);
}
sheet.addValidationData(validation);
}
public static String convertByExp(String propertyValue, String converterExp, String separator) {
StringBuilder propertyString = new StringBuilder();
String[] convertSource = converterExp.split(",");
for (String item : convertSource) {
String[] itemArray = item.split("=");
if (StringUtils.containsAny(separator, propertyValue)) {
for (String value : propertyValue.split(separator)) {
if (itemArray[0].equals(value)) {
propertyString.append(itemArray[1] + separator);
break;
}
}
} else {
if (itemArray[0].equals(propertyValue)) {
return itemArray[1];
}
}
}
return StringUtils.stripEnd(propertyString.toString(), separator);
}
public static String reverseByExp(String propertyValue, String converterExp, String separator) {
StringBuilder propertyString = new StringBuilder();
String[] convertSource = converterExp.split(",");
for (String item : convertSource) {
String[] itemArray = item.split("=");
if (StringUtils.containsAny(separator, propertyValue)) {
for (String value : propertyValue.split(separator)) {
if (itemArray[1].equals(value)) {
propertyString.append(itemArray[0] + separator);
break;
}
}
} else {
if (itemArray[1].equals(propertyValue)) {
return itemArray[0];
}
}
}
return StringUtils.stripEnd(propertyString.toString(), separator);
}
public static String convertDictByExp(String dictValue, String dictType, String separator) {
return DictUtils.getDictLabel(dictType, dictValue, separator);
}
public static String reverseDictByExp(String dictLabel, String dictType, String separator) {
return DictUtils.getDictValue(dictType, dictLabel, separator);
}
public String dataFormatHandlerAdapter(Object value, Excel excel) {
try {
Object instance = excel.handler().newInstance();
Method formatMethod = excel.handler().getMethod("format", new Class[]{Object.class, String[].class});
value = formatMethod.invoke(instance, value, excel.args());
} catch (Exception e) {
log.error("不能格式化数据 " + excel.handler(), e.getMessage());
}
return Convert.toStr(value);
}
private void addStatisticsData(Integer index, String text, Excel entity) {
if (entity != null && entity.isStatistics()) {
Double temp = 0D;
if (!statistics.containsKey(index)) {
statistics.put(index, temp);
}
try {
temp = Double.valueOf(text);
} catch (NumberFormatException e) {
}
statistics.put(index, statistics.get(index) + temp);
}
}
public void addStatisticsRow() {
if (statistics.size() > 0) {
Row row = sheet.createRow(sheet.getLastRowNum() + 1);
Set<Integer> keys = statistics.keySet();
Cell cell = row.createCell(0);
cell.setCellStyle(styles.get("total"));
cell.setCellValue("合计");
for (Integer key : keys) {
cell = row.createCell(key);
cell.setCellStyle(styles.get("total"));
cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
}
statistics.clear();
}
}
private Object getTargetValue(T vo, Field field, Excel excel) throws Exception {
Object o = field.get(vo);
if (StringUtils.isNotEmpty(excel.targetAttr())) {
String target = excel.targetAttr();
if (target.indexOf(".") > -1) {
String[] targets = target.split("[.]");
for (String name : targets) {
o = getValue(o, name);
}
} else {
o = getValue(o, target);
}
}
return o;
}
private Object getValue(Object o, String name) throws Exception {
if (StringUtils.isNotNull(o) && StringUtils.isNotEmpty(name)) {
Class<?> clazz = o.getClass();
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
o = field.get(o);
}
return o;
}
private void createExcelField() {
this.fields = getFields();
this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
this.maxHeight = getRowHeight();
}
public List<Object[]> getFields() {
List<Object[]> fields = new ArrayList<Object[]>();
List<Field> tempFields = new ArrayList<>();
tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
for (Field field : tempFields) {
if (field.isAnnotationPresent(Excel.class)) {
Excel attr = field.getAnnotation(Excel.class);
if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
field.setAccessible(true);
fields.add(new Object[]{field, attr});
}
}
if (field.isAnnotationPresent(Excels.class)) {
Excels attrs = field.getAnnotation(Excels.class);
Excel[] excels = attrs.value();
for (Excel attr : excels) {
if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
field.setAccessible(true);
fields.add(new Object[]{field, attr});
}
}
}
}
return fields;
}
public short getRowHeight() {
double maxHeight = 0;
for (Object[] os : this.fields) {
Excel excel = (Excel) os[1];
maxHeight = maxHeight > excel.height() ? maxHeight : excel.height();
}
return (short) (maxHeight * 20);
}
public void createWorkbook() {
this.wb = new XSSFWorkbook();
this.sheet = wb.createSheet();
wb.setSheetName(0, sheetName);
this.styles = createStyles(wb);
}
public void createSheet(int sheetNo, int index) {
if (sheetNo > 1 && index > 0) {
this.sheet = wb.createSheet();
this.createTitle();
wb.setSheetName(index, sheetName + index);
}
}
public Object getCellValue(Row row, int column) {
if (row == null) {
return row;
}
Object val = "";
try {
Cell cell = row.getCell(column);
if (StringUtils.isNotNull(cell)) {
if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) {
val = cell.getNumericCellValue();
if (DateUtil.isCellDateFormatted(cell)) {
val = DateUtil.getJavaDate((Double) val);
} else {
if ((Double) val % 1 != 0) {
val = new BigDecimal(val.toString());
} else {
val = new DecimalFormat("0").format(val);
}
}
} else if (cell.getCellType() == CellType.STRING) {
val = cell.getStringCellValue();
} else if (cell.getCellType() == CellType.BOOLEAN) {
val = cell.getBooleanCellValue();
} else if (cell.getCellType() == CellType.ERROR) {
val = cell.getErrorCellValue();
}
}
} catch (Exception e) {
return val;
}
return val;
}
private boolean isRowEmpty(Row row) {
if (row == null) {
return true;
}
for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
Cell cell = row.getCell(i);
if (cell != null && cell.getCellType() != CellType.BLANK) {
return false;
}
}
return true;
}
public void Cascade(Sheet sheet,int firstRow, int endRow, int firstCol, int endCol) {
log.info("省市县级联选择模板下载开始");
List<AreaVo> areaCache = AreaUtils.getAreaCache();
List<String> provinceArr = areaCache.stream().filter((e)-> e.getId() != 0L).map(AreaVo::getName).collect(Collectors.toList());
Map<String, List<String>> areaMap = new HashMap<>();
areaCache.stream().forEach((e)->{
areaMap.put(e.getName(),e.getChilds().stream().map(AreaVo::getName).collect(Collectors.toList()));
if(!CollectionUtils.isEmpty(e.getChilds())){
e.getChilds().stream().forEach((e1)->{
areaMap.put(e1.getName(),e1.getChilds().stream().map(AreaVo::getName).collect(Collectors.toList()));
});
}
});
Sheet hideSheet = wb.createSheet("area");
int rowId = 0;
Row provinceRow = hideSheet.createRow(rowId++);
provinceRow.createCell(0).setCellValue("省列表");
for (int i = 0; i < provinceArr.size(); i++) {
Cell provinceCell = provinceRow.createCell(i + 1);
provinceCell.setCellValue(provinceArr.get(i));
}
Iterator<String> keyIterator = areaMap.keySet().iterator();
while (keyIterator.hasNext()) {
String key = keyIterator.next();
List<String> son = areaMap.get(key);
Row row = hideSheet.createRow(rowId++);
row.createCell(0).setCellValue(key);
for (int i = 0; i < son.size(); i++) {
Cell cell = row.createCell(i + 1);
cell.setCellValue(son.get(i));
}
String range = getRange(1, rowId, son.size());
Name name = wb.createName();
name.setNameName(key);
String formula = "area!" + range;
name.setRefersToFormula(formula);
}
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper((XSSFSheet) sheet);
DataValidationConstraint provConstraint = dvHelper.createExplicitListConstraint(provinceArr.toArray(new String[] {}));
CellRangeAddressList provRangeAddressList = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
DataValidation provinceDataValidation = dvHelper.createValidation(provConstraint, provRangeAddressList);
provinceDataValidation.createErrorBox("error", "请选择正确的省份");
provinceDataValidation.setShowErrorBox(true);
provinceDataValidation.setSuppressDropDownArrow(true);
sheet.addValidationData(provinceDataValidation);
for (int i = 2; i < endRow; i++) {
setDataValidation(getExcelColumnLabel(firstCol), (XSSFSheet) sheet, i, firstCol+2);
setDataValidation(getExcelColumnLabel(firstCol+1), (XSSFSheet) sheet, i, firstCol+3);
}
}
private static String getExcelColumnLabel(int iCol) {
String strCol = "";
int baseCol = 65 + iCol;
if (baseCol > 90) {
int i2 = 0;
if ((baseCol - 90) / 26 > 0) {
i2 = 65 + ((baseCol - 90 - 1) / 26);
} else {
i2 = 65;
}
int i1 = ((baseCol - 90 - 1) % 26);
i1 = 65 + i1;
strCol = String.valueOf((char) i2) + String.valueOf((char) i1);
} else {
strCol = String.valueOf((char) baseCol);
}
return strCol;
}
public void setDataValidation(String offset, XSSFSheet sheet, int rowNum, int colNum) {
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
DataValidation data_validation_list;
data_validation_list = getDataValidationByFormula("INDIRECT($" + offset + (rowNum) + ")", rowNum, colNum, dvHelper);
sheet.addValidationData(data_validation_list);
}
private DataValidation getDataValidationByFormula(String formulaString, int naturalRowIndex, int naturalColumnIndex,
XSSFDataValidationHelper dvHelper) {
XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper.createFormulaListConstraint(formulaString);
int firstRow = naturalRowIndex - 1;
int lastRow = naturalRowIndex - 1;
int firstCol = naturalColumnIndex - 1;
int lastCol = naturalColumnIndex - 1;
CellRangeAddressList regions = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
XSSFDataValidation data_validation_list = (XSSFDataValidation) dvHelper.createValidation(dvConstraint, regions);
data_validation_list.setEmptyCellAllowed(false);
if (data_validation_list instanceof XSSFDataValidation) {
data_validation_list.setSuppressDropDownArrow(true);
data_validation_list.setShowErrorBox(true);
} else {
data_validation_list.setSuppressDropDownArrow(false);
}
data_validation_list.createPromptBox("下拉选择提示", "请使用下拉方式选择合适的值!");
data_validation_list.createErrorBox("选择错误提示", "你输入的值未在备选列表中,请下拉选择合适的值!");
return data_validation_list;
}
public static String getRange(int offset, int rowId, int colCount) {
char start = (char) ('A' + offset);
if (colCount <= 25) {
char end = (char) (start + colCount - 1);
return "$" + start + "$" + rowId + ":$" + end + "$" + rowId;
} else {
char endPrefix = 'A';
char endSuffix = 'A';
if ((colCount - 25) / 26 == 0 || colCount == 51) {
if ((colCount - 25) % 26 == 0) {
endSuffix = (char) ('A' + 25);
} else {
endSuffix = (char) ('A' + (colCount - 25) % 26 - 1);
}
} else {
if ((colCount - 25) % 26 == 0) {
endSuffix = (char) ('A' + 25);
endPrefix = (char) (endPrefix + (colCount - 25) / 26 - 1);
} else {
endSuffix = (char) ('A' + (colCount - 25) % 26 - 1);
endPrefix = (char) (endPrefix + (colCount - 25) / 26);
}
}
return "$" + start + "$" + rowId + ":$" + endPrefix + endSuffix + "$" + rowId;
}
}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.math.BigDecimal;
import com.bootplant.common.core.utils.poi.ExcelHandlerAdapter;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Excel
{
public int sort() default Integer.MAX_VALUE;
public String name() default "";
public String dateFormat() default "";
public String dictType() default "";
public boolean AreaType() default false;
public String readConverterExp() default "";
public String separator() default ",";
public int scale() default -1;
public int roundingMode() default BigDecimal.ROUND_HALF_EVEN;
public ColumnType cellType() default ColumnType.STRING;
public double height() default 14;
public double width() default 16;
public String suffix() default "";
public String defaultValue() default "";
public String prompt() default "";
public String[] combo() default {};
public boolean isExport() default true;
public String targetAttr() default "";
public boolean isStatistics() default false;
public Align align() default Align.AUTO;
public Class<?> handler() default ExcelHandlerAdapter.class;
public String[] args() default {};
public enum Align
{
AUTO(0), LEFT(1), CENTER(2), RIGHT(3);
private final int value;
Align(int value)
{
this.value = value;
}
public int value()
{
return this.value;
}
}
Type type() default Type.ALL;
public enum Type
{
ALL(0), EXPORT(1), IMPORT(2);
private final int value;
Type(int value)
{
this.value = value;
}
public int value()
{
return this.value;
}
}
public enum ColumnType
{
NUMERIC(0), STRING(1), IMAGE(2);
private final int value;
ColumnType(int value)
{
this.value = value;
}
public int value()
{
return this.value;
}
}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Excels
{
Excel[] value();
}
import com.bootplant.common.core.constant.RedisKey;
import com.bootplant.common.core.model.AreaVo;
import com.bootplant.common.core.service.RedisService;
import java.util.List;
public class AreaUtils {
public static List<AreaVo> getAreaCache() {
List<AreaVo> areaVos = SpringUtils.getBean(RedisService.class).getCacheList(RedisKey.SYS_AREA_ALL);
return areaVos;
}
}
import com.bootplant.common.core.model.SysDictData;
import com.bootplant.common.core.service.RedisService;
import org.springframework.util.CollectionUtils;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class DictUtils {
public static final String SEPARATOR = ",";
public static final String SYS_DICT_KEY = "sys_dict:";
public static void setDictCache(String key, List<SysDictData> dictDatas) {
SpringUtils.getBean(RedisService.class).setCacheObject(getCacheKey(key), dictDatas);
}
public static List<SysDictData> getDictCache(String key) {
Object cacheObj = SpringUtils.getBean(RedisService.class).getCacheObject(getCacheKey(key));
if (StringUtils.isNotNull(cacheObj)) {
return StringUtils.cast(cacheObj);
}
return null;
}
public static List<String> getDictLabelList(String key) {
List<SysDictData> dictCache = getDictCache(key);
if (!CollectionUtils.isEmpty(dictCache)) {
List<String> labelStr = dictCache.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
return labelStr;
}
return null;
}
public static String getDictLabel(String dictType, String dictValue) {
return getDictLabel(dictType, dictValue, SEPARATOR);
}
public static String getDictValue(String dictType, String dictLabel) {
return getDictValue(dictType, dictLabel, SEPARATOR);
}
public static String getDictLabel(String dictType, String dictValue, String separator) {
StringBuilder propertyString = new StringBuilder();
List<SysDictData> datas = getDictCache(dictType);
if (StringUtils.containsAny(separator, dictValue) && StringUtils.isNotEmpty(datas)) {
for (SysDictData dict : datas) {
for (String value : dictValue.split(separator)) {
if (value.equals(dict.getDictValue())) {
propertyString.append(dict.getDictLabel()).append(separator);
break;
}
}
}
} else {
for (SysDictData dict : datas) {
if (dictValue.equals(dict.getDictValue())) {
return dict.getDictLabel();
}
}
}
return StringUtils.stripEnd(propertyString.toString(), separator);
}
public static String getDictValue(String dictType, String dictLabel, String separator) {
StringBuilder propertyString = new StringBuilder();
List<SysDictData> datas = getDictCache(dictType);
if (StringUtils.containsAny(separator, dictLabel) && StringUtils.isNotEmpty(datas)) {
for (SysDictData dict : datas) {
for (String label : dictLabel.split(separator)) {
if (label.equals(dict.getDictLabel())) {
propertyString.append(dict.getDictValue()).append(separator);
break;
}
}
}
} else {
for (SysDictData dict : datas) {
if (dictLabel.equals(dict.getDictLabel())) {
return dict.getDictValue();
}
}
}
return StringUtils.stripEnd(propertyString.toString(), separator);
}
public static void removeDictCache(String key) {
SpringUtils.getBean(RedisService.class).deleteObject(getCacheKey(key));
}
public static void clearDictCache() {
Collection<String> keys = SpringUtils.getBean(RedisService.class).keys(SYS_DICT_KEY + "*");
SpringUtils.getBean(RedisService.class).deleteObject(keys);
}
public static String getCacheKey(String configKey) {
return SYS_DICT_KEY + configKey;
}
}
package com.bootplant.common.core.model;
import com.bootplant.common.core.web.domain.BaseEntity;
import lombok.Data;
import java.util.Set;
@Data
public class AreaVo extends BaseEntity
{
private Long id;
private String name;
private Long pid;
private Set<AreaVo> childs;
}