自定义注解
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target(FIELD)
@Documented
public @interface ExcelExportAnnotation {
String title() default "";
int order() default 0;
}
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.hikvision.idatafusion.dgdpsiot.common.annotation.ExcelExportAnnotation;
import java.lang.reflect.Field;
import java.util.*;
/**
* @author hanrensong
* @date 2021/4/24
*/
public class ExcelUtil {
public static <T> void listToSheet(Workbook workbook, List<? extends Object> list, Class<T> cls, String sheetName) {
if(workbook==null) {
return;
}
Sheet sheet = null;
if(StringUtils.isNotBlank(sheetName)) {
sheet = workbook.createSheet(sheetName);
}else {
sheet = workbook.createSheet();
}
Row header = sheet.createRow(0);
writeHead(header,cls);
if (CollectionUtils.isNotEmpty(list)) {
Map<Integer, Field> fields = new HashMap<>();
List<Integer> fieldOrders = new ArrayList<>();
parseClass(cls,fields,fieldOrders);
for(int i=0;i<list.size();i++) {
Object t = list.get(i);
Row row = sheet.createRow(i+1);
for(int j=0; j<fieldOrders.size();j++) {
Cell cell = row.createCell(j);
Field field = fields.get(fieldOrders.get(j));
try {
field.setAccessible(true);
Object value = field.get(t);
if(value != null) {
cell.setCellValue(String.valueOf(value));
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
/**
* @param cls
* @param fieldMap
* @param fieldOrders
*/
private static <T> void parseClass(Class<T> cls, Map<Integer, Field> fieldMap, List<Integer> fieldOrders) {
Field[] fields = cls.getDeclaredFields();
for(Field field : fields) {
if(field.isAnnotationPresent(ExcelExportAnnotation.class)) {
ExcelExportAnnotation annotation = field.getAnnotation(ExcelExportAnnotation.class);
Integer order = new Integer(annotation.order());
fieldMap.put(order, field);
fieldOrders.add(order);
}
}
Collections.sort(fieldOrders);
}
/**
* @param row
* @param cls
*/
private static <T> void writeHead(Row row, Class<T> cls) {
Field[] fields = cls.getDeclaredFields();
Map<Integer,String> titles = new HashMap<>();
List<Integer> orders = new ArrayList<>();
for(Field field : fields) {
if(field.isAnnotationPresent(ExcelExportAnnotation.class)) {
ExcelExportAnnotation annotation = field.getAnnotation(ExcelExportAnnotation.class);
Integer order = new Integer(annotation.order());
titles.put(order, annotation.title());
orders.add(order);
}
}
Collections.sort(orders);
for(Integer i : orders) {
Cell cell = row.createCell(i-1);
cell.setCellValue(titles.get(i));
}
}
public static <T> List<T> sheetToList(Sheet sheet, Class<T> voClass, int headerRowNumber){
if(sheet == null || voClass==null ){
return null;
}
List<T> result = new ArrayList<>();
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
if(row.getRowNum()<headerRowNumber) {
continue;
}
parseRow(result,row,voClass);
}
return result;
}
/**
* @param result
* @param row
* @param voClass
*/
private static <T> void parseRow(List<T> result, Row row, Class<T> voClass) {
Iterator<Cell> cellIterator = row.cellIterator();
T t = null;
try {
t = voClass.newInstance();
DataFormatter formatter = new DataFormatter();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
Field field = getField(cell.getColumnIndex()+1,voClass);
if(field!=null) {
field.setAccessible(true);
field.set(t, formatter.formatCellValue(cell));
}
}
} catch (Exception e) {
e.printStackTrace();
}
if(t!=null) {
result.add(t);
}
}
/**
* @param columnIndex
* @param voClass
*/
private static <T> Field getField(int columnIndex, Class<T> voClass) {
Field[] fields = voClass.getDeclaredFields();
for(Field field : fields) {
if(field.isAnnotationPresent(ExcelExportAnnotation.class)) {
ExcelExportAnnotation annotation = field.getAnnotation(ExcelExportAnnotation.class);
if(annotation.order()==columnIndex) {
return field;
}
}
}
return null;
}
public static void mergeSheet(XSSFWorkbook workbook, int sheetIndex, int cellNum) {
Sheet sheet = workbook.getSheetAt(sheetIndex);
if (sheet.getLastRowNum() > 2) {
Iterator<Row> sheetIterator = sheet.rowIterator();
int rowStart =1;
String modelName = sheet.getRow(1).getCell(cellNum).getStringCellValue();
while(sheetIterator.hasNext()) {
Row row = sheetIterator.next();
if(row.getRowNum()<2) {
continue;
}
String cellValue = row.getCell(cellNum).getStringCellValue();
if(cellValue.equals(modelName)) {
continue;
}else {
if(rowStart!=(row.getRowNum()-1)) {
CellRangeAddress region = new CellRangeAddress(rowStart, row.getRowNum()-1, cellNum, cellNum);
sheet.addMergedRegion(region);
}
rowStart = row.getRowNum();
modelName = cellValue;
}
}
if(rowStart!=sheet.getLastRowNum()) {
CellRangeAddress region = new CellRangeAddress(rowStart, sheet.getLastRowNum(), cellNum, cellNum);
sheet.addMergedRegion(region);
}
}
}
// public static void main(String[] args) throws IOException {
//
//
// XSSFWorkbook workbook = new XSSFWorkbook();
//
// XSSFCellStyle style = workbook.createCellStyle();
// style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// Sheet sheet = workbook.createSheet("sheet");
//
// Row row0 = sheet.createRow(0);
// Cell cell_00 = row0.createCell(0);
// cell_00.setCellStyle(style);
// cell_00.setCellValue("日期");
// Cell cell_01 = row0.createCell(1);
// cell_01.setCellStyle(style);
// cell_01.setCellValue("午别");
// Row row1 = sheet.createRow(1);
// Cell cell_10 = row1.createCell(0);
// cell_10.setCellStyle(style);
// cell_10.setCellValue("20180414");
// Cell cell_11 = row1.createCell(1);
// cell_11.setCellStyle(style);
// cell_11.setCellValue("上午");
//
// Row row2 = sheet.createRow(2);
// Cell cell_20 = row2.createCell(0);
// cell_20.setCellStyle(style);
// cell_20.setCellValue("20180413");
// Cell cell_21 = row2.createCell(1);
// cell_21.setCellStyle(style);
// cell_21.setCellValue("下午");
//
// // 合并日期占两行(4个参数,分别为起始行,结束行,起始列,结束列)
// // 行和列都是从0开始计数,且起始结束都会合并
// // 这里是合并excel中日期的两行为一行
// CellRangeAddress region = new CellRangeAddress(1, 2, 0, 0);
// sheet.addMergedRegion(region);
//
// File file = new File("E:\\demo1.xls");
// FileOutputStream fout = new FileOutputStream(file);
// workbook.write(fout);
// fout.close();
//
// }
}