Chinaunix首页 | 论坛 | 博客
  • 博客访问: 165170
  • 博文数量: 56
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 593
  • 用 户 组: 普通用户
  • 注册时间: 2014-02-18 09:59
文章分类

全部博文(56)

文章存档

2019年(1)

2018年(26)

2016年(1)

2015年(6)

2014年(22)

我的朋友

分类: Java

2018-06-29 01:27:00


特点描述: 接口已经简化到最优,  导出一个数据源的list, 只需要传入一个List参数,  即可导出与之对应的excel

结构如下
    -adapter 单元格样式
        -CellSimpleStyleHandlerAdapter   数据单元格样式
        -CellStyleHandlerAdapter   样式接口
        -CellTitleStyleHandlerAdapter   标题单元格样式
    -annotation   注解,描述Excel的表头名称,  在Excel中该字段所处的位置
        -FieldMeta   
    -client
        -ExcelClient   导出excel的util入口
        -ExcelManager   
        -SortableField   
    -handler
        -MetaHandler   获取字段上的注解
    -resolver   真正的创建excel, 根据数据源解析Excel的工作簿,以及表头部分
        -DefaultWorkBookResolver   
        -HSSFWorkbookResolver   



1. adapter 单元格样式

CellStyleHandlerAdapter 样式接口

点击(此处)折叠或打开

  1. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  2. import org.apache.poi.hssf.usermodel.HSSFWorkbook;

  3. /**
  4.  * Created by zonor on 17/3/31.
  5.  */
  6. public interface CellStyleHandlerAdapter {

  7.     /**
  8.      * 设置单元格样式
  9.      *
  10.      * @param wb
  11.      * @return
  12.      */
  13.     HSSFCellStyle styleSettings(HSSFWorkbook wb);
  14. }

CellTitleStyleHandlerAdapter   标题单元格样式

点击(此处)折叠或打开

  1. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  2. import org.apache.poi.hssf.usermodel.HSSFFont;
  3. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  4. import org.apache.poi.ss.usermodel.CellStyle;

  5. /**
  6.  * Created by zonor on 17/3/31.
  7.  */
  8. public class CellTitleStyleHandlerAdapter implements CellStyleHandlerAdapter {

  9.     /**
  10.      * 设置单元格样式
  11.      *
  12.      * @param wb
  13.      * @return
  14.      */
  15.     public HSSFCellStyle styleSettings(HSSFWorkbook wb) {
  16.         HSSFCellStyle style = wb.createCellStyle();
  17.         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  18.         style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

  19.         //设置字体
  20.         HSSFFont font = wb.createFont();
  21.         font.setBold(true);
  22.         style.setFont(font);
  23.         return style;
  24.     }
  25. }

CellSimpleStyleHandlerAdapter   数据单元格样式

点击(此处)折叠或打开

  1. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  2. import org.apache.poi.hssf.usermodel.HSSFWorkbook;

  3. /**
  4.  * Created by zonor on 17/3/31.
  5.  */
  6. public class CellSimpleStyleHandlerAdapter implements CellStyleHandlerAdapter {

  7.     /**
  8.      * 设置单元格样式
  9.      *
  10.      * @param wb
  11.      * @return
  12.      */
  13.     public HSSFCellStyle styleSettings(HSSFWorkbook wb) {
  14.         HSSFCellStyle style = wb.createCellStyle();
  15.         return style;
  16.     }
  17. }


2. annotation   
FieldMeta注解, 描述Excel的表头名称,  在Excel中该字段所处的位置

点击(此处)折叠或打开

  1. import java.lang.annotation.*;

  2. /**
  3.  * Created by zonor on 17/3/30.
  4.  */
  5. @Target(ElementType.FIELD)
  6. @Retention(RetentionPolicy.RUNTIME)
  7. @Documented
  8. @Inherited
  9. public @interface FieldMeta {

  10.     /**
  11.      * Excel的表头
  12.      * @return
  13.      */
  14.     String title() default "";

  15.     /**
  16.      * 在Excel中该字段所处的位置
  17.      * @return
  18.      */
  19.     int order() default 0;
  20. }


3.handler 
   MetaHandler   获取字段上的注解

点击(此处)折叠或打开

  1. import org.mogujie.iip.commons.excel.annotation.FieldMeta;
  2. import org.mogujie.iip.commons.excel.client.SortableField;

  3. import java.lang.reflect.Field;
  4. import java.util.ArrayList;
  5. import java.util.Collections;
  6. import java.util.Comparator;
  7. import java.util.List;

  8. /**
  9.  * Created by zonor on 17/3/30.
  10.  *
  11.  */
  12. public class MetaHandler<T> {

  13.     private Class<T> entity;

  14.     public MetaHandler(Class<T> entity) {
  15.         this.entity = entity;
  16.         init();
  17.     }

  18.     public List<SortableField> init() {
  19.         List<SortableField> list = new ArrayList<SortableField>();

  20.         if (null != entity) {
  21.             Field[] fields = entity.getDeclaredFields();

  22.             for (Field field : fields) {
  23.                 //获取字段上的注解
  24.                 FieldMeta fieldMeta = field.getAnnotation(FieldMeta.class);
  25.                 if (null != fieldMeta) {
  26.                     SortableField sf = new SortableField(fieldMeta, field);
  27.                     list.add(sf);
  28.                 }
  29.             }

  30.             //对设置的字段的元数据中的order进行排序
  31.             Collections.sort(list, new Comparator<SortableField>() {
  32.                 public int compare(SortableField o1, SortableField o2) {
  33.                     return o1.getMeta().order() - o2.getMeta().order();
  34.                 }
  35.             });
  36.         }

  37.         return list;
  38.     }
  39. }


4.client 
        -ExcelClient   导出excel的util入口
        -ExcelManager   默认属性管理
        -SortableField     注解信息管理

点击(此处)折叠或打开

  1. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  2. import org.mogujie.iip.commons.excel.handler.MetaHandler;
  3. import org.mogujie.iip.commons.excel.resolver.HSSFWorkbookResolver;

  4. import javax.servlet.http.HttpServletResponse;
  5. import java.io.OutputStream;
  6. import java.util.List;

  7. /**
  8.  * Created by zonor on 17/3/30.
  9.  */
  10. public class ExcelClient {

  11.     private ExcelManager manager;

  12.     public ExcelManager getManager() {
  13.         return manager;
  14.     }

  15.     public void setManager(ExcelManager manager) {
  16.         this.manager = manager;
  17.     }

  18.     /**
  19.      * 加载管理器,实例化还是注入都必须要优先调用
  20.      */
  21.     public void init() {
  22.         if (null == this.manager) {
  23.             this.manager = new ExcelManager();
  24.             this.manager.init();
  25.         }
  26.     }

  27.     /**
  28.      * 导出
  29.      *
  30.      * @param fileName
  31.      * @param datasource
  32.      * @param response
  33.      * @param workbookName
  34.      * @param <T>
  35.      * @throws Exception
  36.      */
  37.     public <T> void export(String fileName, List<T> datasource, HttpServletResponse response, String workbookName) throws Exception {
  38.         HSSFWorkbookResolver resolver = this.manager.getResolver();
  39.         MetaHandler<T> metaHandler = new MetaHandler<T>((Class<T>) datasource.get(0).getClass());
  40.         HSSFWorkbook wb = resolver.resolverWorkBook(datasource,
  41.                 metaHandler,
  42.                 workbookName,
  43.                 this.manager.getTitleStyleAdapter(),
  44.                 this.manager.getSimpleStyleAdapter());

  45.         response.setContentType("application/vnd.ms-excel");
  46.         response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xls");
  47.         OutputStream ouputStream = response.getOutputStream();
  48.         wb.write(ouputStream);
  49.         ouputStream.flush();
  50.         ouputStream.close();
  51.     }

  52.     /**
  53.      * 导出
  54.      *
  55.      * @param fileName
  56.      * @param datasource
  57.      * @param response
  58.      * @param <T>
  59.      * @throws Exception
  60.      */
  61.     public <T> void export(String fileName, List<T> datasource, HttpServletResponse response) throws Exception {
  62.         HSSFWorkbookResolver resolver = this.manager.getResolver();
  63.         MetaHandler<T> metaHandler = new MetaHandler<T>((Class<T>) datasource.get(0).getClass());
  64.         HSSFWorkbook wb = resolver.resolverWorkBook(datasource,
  65.                 metaHandler,
  66.                 this.manager.getTitleStyleAdapter(),
  67.                 this.manager.getSimpleStyleAdapter());

  68.         response.setContentType("application/vnd.ms-excel");
  69.         response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xls");
  70.         OutputStream ouputStream = response.getOutputStream();
  71.         wb.write(ouputStream);
  72.         ouputStream.flush();
  73.         ouputStream.close();
  74.     }

  75.     /**
  76.      * 导出
  77.      * @param datasource
  78.      * @param <T>
  79.      * @return
  80.      * @throws Exception
  81.      */
  82.     public <T> HSSFWorkbook export(List<T> datasource) throws Exception {
  83.         HSSFWorkbookResolver resolver = this.manager.getResolver();
  84.         MetaHandler<T> metaHandler = new MetaHandler<T>((Class<T>) datasource.get(0).getClass());
  85.         HSSFWorkbook wb = resolver.resolverWorkBook(datasource,
  86.                 metaHandler,
  87.                 this.manager.getTitleStyleAdapter(),
  88.                 this.manager.getSimpleStyleAdapter());

  89.       return wb;
  90.     }
  91. }

点击(此处)折叠或打开

  1. import org.mogujie.iip.commons.excel.adapter.CellSimpleStyleHandlerAdapter;
  2. import org.mogujie.iip.commons.excel.adapter.CellStyleHandlerAdapter;
  3. import org.mogujie.iip.commons.excel.adapter.CellTitleStyleHandlerAdapter;
  4. import org.mogujie.iip.commons.excel.handler.MetaHandler;
  5. import org.mogujie.iip.commons.excel.resolver.DefaultWorkBookResolver;
  6. import org.mogujie.iip.commons.excel.resolver.HSSFWorkbookResolver;

  7. /**
  8.  * Created by zonor on 17/3/30.
  9.  */
  10. public class ExcelManager {

  11.     /**
  12.      * workbook解析器
  13.      */
  14.     private HSSFWorkbookResolver resolver;

  15.     /**
  16.      * 标题样式
  17.      */
  18.     private CellStyleHandlerAdapter titleStyleAdapter;

  19.     /**
  20.      * 数据样式
  21.      */
  22.     private CellStyleHandlerAdapter simpleStyleAdapter;

  23.     public HSSFWorkbookResolver getResolver() {
  24.         return resolver;
  25.     }

  26.     public void setResolver(HSSFWorkbookResolver resolver) {
  27.         this.resolver = resolver;
  28.     }

  29.     public CellStyleHandlerAdapter getTitleStyleAdapter() {
  30.         return titleStyleAdapter;
  31.     }

  32.     public void setTitleStyleAdapter(CellStyleHandlerAdapter titleStyleAdapter) {
  33.         this.titleStyleAdapter = titleStyleAdapter;
  34.     }

  35.     public CellStyleHandlerAdapter getSimpleStyleAdapter() {
  36.         return simpleStyleAdapter;
  37.     }

  38.     public void setSimpleStyleAdapter(CellStyleHandlerAdapter simpleStyleAdapter) {
  39.         this.simpleStyleAdapter = simpleStyleAdapter;
  40.     }

  41.     public void init() {
  42.         this.resolver = new DefaultWorkBookResolver();
  43.         this.titleStyleAdapter = new CellTitleStyleHandlerAdapter();
  44.         this.simpleStyleAdapter = new CellSimpleStyleHandlerAdapter();
  45.     }
  46. }


点击(此处)折叠或打开

  1. import org.mogujie.iip.commons.excel.annotation.FieldMeta;

  2. import java.lang.reflect.Field;

  3. /**
  4.  * 字段以及meta信息的帮助类
  5.  * Created by zonor on 17/3/30.
  6.  */
  7. public class SortableField {

  8.     public SortableField() {
  9.         super();
  10.     }

  11.     public SortableField(FieldMeta meta, Field field) {
  12.         super();
  13.         this.meta = meta;
  14.         this.field = field;
  15.         this.name = field.getName();
  16.         this.type = field.getType();
  17.     }

  18.     public SortableField(FieldMeta meta, String name, Class<?> type) {
  19.         super();
  20.         this.meta = meta;
  21.         this.name = name;
  22.         this.type = type;
  23.     }

  24.     private FieldMeta meta;
  25.     private Field field;
  26.     private String name;
  27.     private Class<?> type;

  28.     public FieldMeta getMeta() {
  29.         return meta;
  30.     }

  31.     public void setMeta(FieldMeta meta) {
  32.         this.meta = meta;
  33.     }

  34.     public Field getField() {
  35.         return field;
  36.     }

  37.     public void setField(Field field) {
  38.         this.field = field;
  39.     }

  40.     public String getName() {
  41.         return name;
  42.     }

  43.     public void setName(String name) {
  44.         this.name = name;
  45.     }

  46.     public Class<?> getType() {
  47.         return type;
  48.     }

  49.     public void setType(Class<?> type) {
  50.         this.type = type;
  51.     }
  52. }


5. resolver   真正的创建excel, 根据数据源解析Excel的工作簿,以及表头部分
        -DefaultWorkBookResolver   
        -HSSFWorkbookResolver   

点击(此处)折叠或打开

  1. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  2. import org.mogujie.iip.commons.excel.adapter.CellStyleHandlerAdapter;
  3. import org.mogujie.iip.commons.excel.handler.MetaHandler;

  4. import java.util.List;

  5. /**
  6.  * Created by zonor on 17/3/30.
  7.  */
  8. public interface HSSFWorkbookResolver {

  9.     /**
  10.      * 根据数据源解析Excel的工作簿,以及表头部分
  11.      * @param <T>
  12.      * @param dataSource
  13.      * @param handler
  14.      * @param workbookName
  15.      * @param titleStyleAdapter
  16.      *@param simpleStyleAdapter @return
  17.      */
  18.     <T> HSSFWorkbook resolverWorkBook(List<T> dataSource, MetaHandler<T> handler, String workbookName, CellStyleHandlerAdapter titleStyleAdapter, CellStyleHandlerAdapter simpleStyleAdapter) throws Exception;

  19.     /**
  20.      * 根据数据源解析Excel的工作簿,以及表头部分
  21.      * @param <T>
  22.      * @param dataSource
  23.      * @param handler
  24.      * @param titleStyleAdapter
  25.      *@param simpleStyleAdapter @return
  26.      */
  27.     <T> HSSFWorkbook resolverWorkBook(List<T> dataSource, MetaHandler<T> handler, CellStyleHandlerAdapter titleStyleAdapter, CellStyleHandlerAdapter simpleStyleAdapter) throws Exception;
  28. }

点击(此处)折叠或打开

  1. import org.apache.commons.beanutils.BeanUtils;
  2. import org.apache.commons.lang.StringUtils;
  3. import org.apache.poi.hssf.usermodel.*;
  4. import org.mogujie.iip.commons.excel.adapter.CellStyleHandlerAdapter;
  5. import org.mogujie.iip.commons.excel.handler.MetaHandler;
  6. import org.mogujie.iip.commons.excel.client.SortableField;

  7. import java.util.List;

  8. /**
  9.  * Created by zonor on 17/3/30.
  10.  */
  11. public class DefaultWorkBookResolver implements HSSFWorkbookResolver {

  12.     /**
  13.      * 根据数据源解析Excel的工作簿,以及表头部分
  14.      *
  15.      * @param dataSource
  16.      * @param handler
  17.      * @param workbookName
  18.      * @param titleStyleAdapter
  19.      * @param simpleStyleAdapter @return
  20.      */
  21.     public <T> HSSFWorkbook resolverWorkBook(List<T> dataSource,
  22.                                              MetaHandler<T> handler,
  23.                                              String workbookName,
  24.                                              CellStyleHandlerAdapter titleStyleAdapter,
  25.                                              CellStyleHandlerAdapter simpleStyleAdapter) throws Exception {
  26.         //获取字段的元数据信息
  27.         List<SortableField> sortableFieldList = handler.init();

  28.         if (StringUtils.isEmpty(workbookName)) {
  29.             workbookName = "sheet1";
  30.         }

  31.         //创建工作簿
  32.         HSSFWorkbook wb = new HSSFWorkbook();
  33.         HSSFSheet sheet = wb.createSheet(workbookName);
  34.         HSSFRow row = sheet.createRow(0);
  35.         HSSFCellStyle style = titleStyleAdapter.styleSettings(wb);

  36.         //绘制标题行
  37.         for (int i = 0; i < sortableFieldList.size(); i++) {
  38.             HSSFCell cell = row.createCell(i);
  39.             cell.setCellStyle(style);
  40.             cell.setCellValue(sortableFieldList.get(i).getMeta().title());
  41.         }

  42.         //绘制数据行
  43.         HSSFCellStyle hssfCellStyle = simpleStyleAdapter.styleSettings(wb);
  44.         for (int i = 0; i < dataSource.size(); i++) {
  45.             HSSFRow dataRow = sheet.createRow(i + 1);
  46.             T data = dataSource.get(i);

  47.             for (int j = 0; j < sortableFieldList.size(); j++) {
  48.                 SortableField sortableField = sortableFieldList.get(j);
  49.                 String property = BeanUtils.getProperty(data, sortableField.getName());

  50.                 HSSFCell cell = dataRow.createCell(j);
  51.                 cell.setCellStyle(hssfCellStyle);
  52.                 cell.setCellValue(property);
  53.             }

  54.         }

  55.         return wb;
  56.     }

  57.     /**
  58.      * 根据数据源解析Excel的工作簿,以及表头部分
  59.      *
  60.      * @param dataSource
  61.      * @param handler
  62.      * @param titleStyleAdapter
  63.      * @param simpleStyleAdapter @return
  64.      */
  65.     public <T> HSSFWorkbook resolverWorkBook(List<T> dataSource,
  66.                                              MetaHandler<T> handler,
  67.                                              CellStyleHandlerAdapter titleStyleAdapter,
  68.                                              CellStyleHandlerAdapter simpleStyleAdapter) throws Exception {
  69.         return resolverWorkBook(dataSource, handler, "", titleStyleAdapter, simpleStyleAdapter);
  70.     }
  71. }


测试, 看着确实非常简洁了
导出的实体对象

点击(此处)折叠或打开

  1. @Data
  2. public class Student {
  3.     @FieldMeta(title = "id", order = 0)
  4.     private int id;

  5.     @FieldMeta(title = "姓名", order = 2)
  6.     private String name;

  7.     @FieldMeta(title = "性别", order = 1)
  8.     private String sex;

  9.     public Student(int id, String name, String sex) {
  10.         this.id = id;
  11.         this.name = name;
  12.         this.sex = sex;
  13.     }
  14. }
导出代码

点击(此处)折叠或打开

  1. /**
  2.  */
  3. public class ExcelClientTest {
  4.     public static void main(String [] args) throws Exception {

  5.         ExcelClient excelClient = new ExcelClient();
  6.         excelClient.init();

  7.         List<Student> list = new ArrayList();
  8.         list.add(new Student(111, "张三asdf", "男"));
  9.         list.add(new Student(111, "李四asd", "男"));
  10.         list.add(new Student(111, "王五bhasdcfvbhujidsaub", "女"));

  11.         HSSFWorkbook workbook = excelClient.export(list);
  12.         FileOutputStream exportXls = new FileOutputStream("/Users/excel/工单信息表.xls");
  13.         workbook.write(exportXls);
  14.     }

  15. }

结果:








阅读(1861) | 评论(0) | 转发(0) |
0

上一篇:ideal中使用lombok说明

下一篇:远离IDEA卡顿

给主人留下些什么吧!~~