package com.framework.util.excel; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.beanutils.BeanComparator; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.ComparatorUtils; import org.apache.commons.collections.comparators.ComparableComparator; import org.apache.commons.collections.comparators.ComparatorChain; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.framework.util.PropertiesLoader; public class Excel { /** * 个人加,返回路径 * * @param fileType * @param headers * @param excels * @return */ public static Logger LG = LoggerFactory.getLogger(ExcelUtil.class); public final static String excel_format_xls = ".xls"; public final static String excel_format_xlsx = ".xlsx"; public static <T> String exportExcels(String fileType, String[] headers, List<Collection<T>> excels,String filePath) { //String ctxPath = request.getSession().getServletContext().getRealPath(""); String uploadPath = PropertiesLoader.get("UPLOAD_PATH"); //String zipReturnPath = "dd/zip/" + UUID.randomUUID().toString() + ".zip"; List<String> temporaryFilePaths = new ArrayList<>(); String uploadFilePath = ""; if (org.springframework.util.CollectionUtils.isEmpty(excels)) { return ""; } for (Collection<T> collection : excels) { String path = ""; path += filePath; File file = new File(uploadPath + path); file.getParentFile().mkdirs(); // 声明一个工作薄 if ("xls".equals(fileType)) { path += excel_format_xls; HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一个表格 HSSFSheet sheet = workbook.createSheet(); //写入数据 write2XlsSheet(sheet, headers, collection, null, null); //生成文件 try { FileOutputStream fo = new FileOutputStream(uploadPath + path); workbook.write(fo); fo.close(); } catch (IOException e) { e.printStackTrace(); } } else { path += excel_format_xlsx; XSSFWorkbook workbook = new XSSFWorkbook(); // 生成一个表格 XSSFSheet sheet = workbook.createSheet(); //写入数据 write2XlsxSheet(sheet, headers, collection, null, null); //生成文件 try { FileOutputStream fo = new FileOutputStream(uploadPath + path); workbook.write(fo); fo.close(); } catch (IOException e) { e.printStackTrace(); } } //uploadFilePath uploadFilePath = uploadPath + path; } return uploadFilePath; } /** * 每个xlsSheet的写入 * * @param sheet 页签 * @param headers 表头 * @param dataset 数据集合 * @param pattern 日期格式 */ private static <T> void write2XlsxSheet(XSSFSheet sheet, String[] headers, Collection<T> dataset, String pattern, Map<String, Object> colorMap) { // 产生表格标题行 XSSFRow row = sheet.createRow(0); for (int i = 0; i < headers.length; i++) { XSSFCell cell = row.createCell(i); XSSFRichTextString text = new XSSFRichTextString(headers[i]); cell.setCellValue(text); XSSFFont font = sheet.getWorkbook().createFont(); font.setFontHeightInPoints((short) 14);//设置字体大小 XSSFCellStyle style = sheet.getWorkbook().createCellStyle(); if (colorMap != null && (colorMap.get(text.toString()) != null)) { style.setFillForegroundColor((short) colorMap.get(text.toString())); style.setFillPattern(CellStyle.SOLID_FOREGROUND); } style.setFont(font); cell.setCellStyle(style); } // 遍历集合数据,产生数据行 Iterator<T> it = dataset.iterator(); int index = 0; while (it.hasNext()) { index++; row = sheet.createRow(index); T t = (T) it.next(); try { if (t instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) t; int cellNum = 0; for (String k : headers) { if (map.containsKey(k) == false) { LG.error("Map 中 不存在 key [" + k + "]"); continue; } Object value = map.get(k); XSSFCell cell = row.createCell(cellNum); cell.setCellValue((value == null || "null".equals(String.valueOf(value))) ? "" : String.valueOf(value)); cellNum++; } } else { List<FieldForSortting> fields = sortFieldByAnno(t.getClass()); int cellNum = 0; for (int i = 0; i < fields.size(); i++) { XSSFCell cell = row.createCell(cellNum); Field field = fields.get(i).getField(); field.setAccessible(true); Object value = field.get(t); String textValue = null; if (value instanceof Integer) { int intValue = (Integer) value; cell.setCellValue(intValue); } else if (value instanceof Float) { float fValue = (Float) value; cell.setCellValue(fValue); } else if (value instanceof Double) { double dValue = (Double) value; cell.setCellValue(dValue); } else if (value instanceof Long) { long longValue = (Long) value; cell.setCellValue(longValue); } else if (value instanceof Boolean) { boolean bValue = (Boolean) value; cell.setCellValue(bValue); } else if (value instanceof Date) { Date date = (Date) value; SimpleDateFormat sdf = new SimpleDateFormat(pattern); textValue = sdf.format(date); } else if (value instanceof String[]) { String[] strArr = (String[]) value; for (int j = 0; j < strArr.length; j++) { String str = strArr[j]; cell.setCellValue(str); if (j != strArr.length - 1) { cellNum++; cell = row.createCell(cellNum); } } } else if (value instanceof Double[]) { Double[] douArr = (Double[]) value; for (int j = 0; j < douArr.length; j++) { Double val = douArr[j]; // 资料不为空则set Value if (val != null) { cell.setCellValue(val); } if (j != douArr.length - 1) { cellNum++; cell = row.createCell(cellNum); } } } else { // 其它数据类型都当作字符串简单处理 String empty = StringUtils.EMPTY; ExcelCell anno = field.getAnnotation(ExcelCell.class); if (anno != null) { empty = anno.defaultValue(); } textValue = value == null ? empty : value.toString(); } if (textValue != null) { XSSFRichTextString richString = new XSSFRichTextString(textValue); cell.setCellValue(richString); } cellNum++; } } } catch (Exception e) { LG.error(e.toString(), e); } } // 设定自动宽度 for (int i = 0; i < headers.length; i++) { sheet.autoSizeColumn(i); } } /** * 每个xlsSheet的写入 * * @param sheet 页签 * @param headers 表头 * @param dataset 数据集合 * @param pattern 日期格式 */ private static <T> void write2XlsSheet(HSSFSheet sheet, String[] headers, Collection<T> dataset, String pattern, Map<String, Object> colorMap) { // 产生表格标题行 HSSFRow row = sheet.createRow(0); for (int i = 0; i < headers.length; i++) { HSSFCell cell = row.createCell(i); HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text); HSSFFont font = sheet.getWorkbook().createFont(); //font.setFontName("Consolas"); //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); font.setFontHeightInPoints((short) 14);//设置字体大小 HSSFCellStyle style = sheet.getWorkbook().createCellStyle(); style.setFont(font); if (colorMap != null && (colorMap.get(text.toString()) != null)) { style.setFillForegroundColor((short) colorMap.get(text.toString())); style.setFillPattern(CellStyle.SOLID_FOREGROUND); } cell.setCellStyle(style); } // 遍历集合数据,产生数据行 Iterator<T> it = dataset.iterator(); int index = 0; while (it.hasNext()) { index++; row = sheet.createRow(index); T t = (T) it.next(); try { if (t instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) t; int cellNum = 0; for (String k : headers) { if (map.containsKey(k) == false) { LG.error("Map 中 不存在 key [" + k + "]"); continue; } Object value = map.get(k); HSSFCell cell = row.createCell(cellNum); cell.setCellValue((value == null || "null".equals(String.valueOf(value))) ? "" : String.valueOf(value)); cellNum++; } } else { List<FieldForSortting> fields = sortFieldByAnno(t.getClass()); int cellNum = 0; for (int i = 0; i < fields.size(); i++) { HSSFCell cell = row.createCell(cellNum); Field field = fields.get(i).getField(); field.setAccessible(true); Object value = field.get(t); String textValue = null; if (value instanceof Integer) { int intValue = (Integer) value; cell.setCellValue(intValue); } else if (value instanceof Float) { float fValue = (Float) value; cell.setCellValue(fValue); } else if (value instanceof Double) { double dValue = (Double) value; cell.setCellValue(dValue); } else if (value instanceof Long) { long longValue = (Long) value; cell.setCellValue(longValue); } else if (value instanceof Boolean) { boolean bValue = (Boolean) value; cell.setCellValue(bValue); } else if (value instanceof Date) { Date date = (Date) value; SimpleDateFormat sdf = new SimpleDateFormat(pattern); textValue = sdf.format(date); } else if (value instanceof String[]) { String[] strArr = (String[]) value; for (int j = 0; j < strArr.length; j++) { String str = strArr[j]; cell.setCellValue(str); if (j != strArr.length - 1) { cellNum++; cell = row.createCell(cellNum); } } } else if (value instanceof Double[]) { Double[] douArr = (Double[]) value; for (int j = 0; j < douArr.length; j++) { Double val = douArr[j]; // 资料不为空则set Value if (val != null) { cell.setCellValue(val); } if (j != douArr.length - 1) { cellNum++; cell = row.createCell(cellNum); } } } else { // 其它数据类型都当作字符串简单处理 String empty = StringUtils.EMPTY; ExcelCell anno = field.getAnnotation(ExcelCell.class); if (anno != null) { empty = anno.defaultValue(); } textValue = value == null ? empty : value.toString(); } if (textValue != null) { HSSFRichTextString richString = new HSSFRichTextString(textValue); cell.setCellValue(richString); } cellNum++; } } } catch (Exception e) { LG.error(e.toString(), e); } } // 设定自动宽度 for (int i = 0; i < headers.length; i++) { sheet.autoSizeColumn(i); } } /** * 根据annotation的seq排序后的栏位 * * @param clazz * @return */ private static List<FieldForSortting> sortFieldByAnno(Class<?> clazz) { Field[] fieldsArr = clazz.getDeclaredFields(); List<FieldForSortting> fields = new ArrayList<FieldForSortting>(); List<FieldForSortting> annoNullFields = new ArrayList<FieldForSortting>(); for (Field field : fieldsArr) { ExcelCell ec = field.getAnnotation(ExcelCell.class); if (ec == null) { // 没有ExcelCell Annotation 视为不汇入 continue; } int id = ec.index(); fields.add(new FieldForSortting(field, id)); } fields.addAll(annoNullFields); sortByProperties(fields, true, false, "index"); return fields; } @SuppressWarnings("unchecked") private static void sortByProperties(List<? extends Object> list, boolean isNullHigh, boolean isReversed, String... props) { if (CollectionUtils.isNotEmpty(list)) { Comparator<?> typeComp = ComparableComparator.getInstance(); if (isNullHigh == true) { typeComp = ComparatorUtils.nullHighComparator(typeComp); } else { typeComp = ComparatorUtils.nullLowComparator(typeComp); } if (isReversed) { typeComp = ComparatorUtils.reversedComparator(typeComp); } List<Object> sortCols = new ArrayList<Object>(); if (props != null) { for (String prop : props) { sortCols.add(new BeanComparator(prop, typeComp)); } } if (sortCols.size() > 0) { Comparator<Object> sortChain = new ComparatorChain(sortCols); Collections.sort(list, sortChain); } } } }