| | |
| | | import org.apache.poi.ss.usermodel.Row; |
| | | import org.apache.poi.ss.usermodel.Sheet; |
| | | import org.apache.poi.ss.usermodel.Workbook; |
| | | import org.apache.poi.xssf.usermodel.XSSFWorkbook; |
| | | |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.IOException; |
| | |
| | | |
| | | |
| | | |
| | | public static <T> Workbook createXlsx(List<T> list, Class<T> clz) { |
| | | //HSSFWorkbook workbook = new HSSFWorkbook(); |
| | | XSSFWorkbook workbook =new XSSFWorkbook(); |
| | | Sheet sheet = workbook.createSheet(clz.getSimpleName()); |
| | | |
| | | Row header = sheet.createRow(0); |
| | | Field[] fields = Cools.getAllFields(clz); |
| | | int headerIdx = 0; |
| | | for (Field field : fields) { |
| | | if (Modifier.isFinal(field.getModifiers()) |
| | | || Modifier.isStatic(field.getModifiers()) |
| | | || Modifier.isTransient(field.getModifiers())) { |
| | | continue; |
| | | } |
| | | String memo = "Undefined"; |
| | | if (field.isAnnotationPresent(ApiModelProperty.class)) { |
| | | memo = field.getAnnotation(ApiModelProperty.class).value(); |
| | | } |
| | | header.createCell(headerIdx).setCellValue(memo); |
| | | headerIdx++; |
| | | } |
| | | |
| | | int rowIndex = 1; |
| | | for (T t : list) { |
| | | Row row = sheet.createRow(rowIndex++); |
| | | |
| | | int cellIndex = 0; |
| | | for (Field field : fields) { |
| | | if (Modifier.isFinal(field.getModifiers()) |
| | | || Modifier.isStatic(field.getModifiers()) |
| | | || Modifier.isTransient(field.getModifiers())) { |
| | | continue; |
| | | } |
| | | |
| | | field.setAccessible(true); // 此行很重要,特别是字段为private时 |
| | | Object value = null; |
| | | try { |
| | | value = field.get(t); |
| | | } catch (IllegalAccessException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | if (value != null) { |
| | | if (value instanceof Date) { |
| | | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); |
| | | row.createCell(cellIndex).setCellValue(sdf.format((Date) value)); |
| | | } else { |
| | | row.createCell(cellIndex).setCellValue(value.toString()); |
| | | } |
| | | } |
| | | cellIndex++; |
| | | } |
| | | } |
| | | |
| | | for (int i = 0; i <= fields.length; i++) { |
| | | sheet.autoSizeColumn(i); |
| | | } |
| | | |
| | | return workbook; |
| | | } |
| | | |
| | | } |