阿里云服务器免费领卷啦。

捡代码论坛-最全的游戏源码下载技术网站!

 找回密码
 立 即 注 册

QQ登录

只需一步,快速开始

搜索
关于源码区的附件失效或欺骗帖, 处理办法
查看: 2500|回复: 0

Excel文件导出源码

[复制链接]

3

主题

10

回帖

106

积分

注册会员

Rank: 2

积分
106
发表于 2016-1-21 09:22:32 | 显示全部楼层 |阅读模式
  1. /**
  2. * 导出Excel文件
  3. * @author zw
  4. * @version 2015-04-21
  5. */
  6. public class ExportExcel {
  7.         
  8.         private static Logger log = LoggerFactory.getLogger(ExportExcel.class);
  9.                         
  10.         /**
  11.          * 工作薄对象
  12.          */
  13.         private SXSSFWorkbook wb;
  14.         
  15.         /**
  16.          * 工作表对象
  17.          */
  18.         private Sheet sheet;
  19.         
  20.         /**
  21.          * 样式列表
  22.          */
  23.         private Map<String, CellStyle> styles;
  24.         
  25.         /**
  26.          * 当前行号
  27.          */
  28.         private int rownum;
  29.         
  30.         /**
  31.          * 注解列表(Object[]{ ExcelField, Field/Method })
  32.          */
  33.         List<Object[]> annotationList = Lists.newArrayList();
  34.         
  35.         /**
  36.          * 构造函数
  37.          * @param title 表格标题,传“空值”,表示无标题
  38.          * @param cls 实体对象,通过annotation.ExportField获取标题
  39.          */
  40.         public ExportExcel(String title, Class<?> cls){
  41.                 this(title, cls, 1);
  42.         }
  43.         
  44.         /**
  45.          * 构造函数
  46.          * @param title 表格标题,传“空值”,表示无标题
  47.          * @param cls 实体对象,通过annotation.ExportField获取标题
  48.          * @param type 导出类型(1:导出数据;2:导出模板)
  49.          * @param groups 导入分组
  50.          */
  51.         public ExportExcel(String title, Class<?> cls, int type, int... groups){
  52.                 // Get annotation field
  53.                 Field[] fs = cls.getDeclaredFields();
  54.                 for (Field f : fs){
  55.                         ExcelField ef = f.getAnnotation(ExcelField.class);
  56.                         if (ef != null && (ef.type()==0 || ef.type()==type)){
  57.                                 if (groups!=null && groups.length>0){
  58.                                         boolean inGroup = false;
  59.                                         for (int g : groups){
  60.                                                 if (inGroup){
  61.                                                         break;
  62.                                                 }
  63.                                                 for (int efg : ef.groups()){
  64.                                                         if (g == efg){
  65.                                                                 inGroup = true;
  66.                                                                 annotationList.add(new Object[]{ef, f});
  67.                                                                 break;
  68.                                                         }
  69.                                                 }
  70.                                         }
  71.                                 }else{
  72.                                         annotationList.add(new Object[]{ef, f});
  73.                                 }
  74.                         }
  75.                 }
  76.                 // Get annotation method
  77.                 Method[] ms = cls.getDeclaredMethods();
  78.                 for (Method m : ms){
  79.                         ExcelField ef = m.getAnnotation(ExcelField.class);
  80.                         if (ef != null && (ef.type()==0 || ef.type()==type)){
  81.                                 if (groups!=null && groups.length>0){
  82.                                         boolean inGroup = false;
  83.                                         for (int g : groups){
  84.                                                 if (inGroup){
  85.                                                         break;
  86.                                                 }
  87.                                                 for (int efg : ef.groups()){
  88.                                                         if (g == efg){
  89.                                                                 inGroup = true;
  90.                                                                 annotationList.add(new Object[]{ef, m});
  91.                                                                 break;
  92.                                                         }
  93.                                                 }
  94.                                         }
  95.                                 }else{
  96.                                         annotationList.add(new Object[]{ef, m});
  97.                                 }
  98.                         }
  99.                 }
  100.                 // Field sorting
  101.                 Collections.sort(annotationList, new Comparator<Object[]>() {
  102.                         public int compare(Object[] o1, Object[] o2) {
  103.                                 return new Integer(((ExcelField)o1[0]).sort()).compareTo(
  104.                                                 new Integer(((ExcelField)o2[0]).sort()));
  105.                         };
  106.                 });
  107.                 // Initialize
  108.                 List<String> headerList = Lists.newArrayList();
  109.                 for (Object[] os : annotationList){
  110.                         String t = ((ExcelField)os[0]).title();
  111.                         // 如果是导出,则去掉注释
  112.                         if (type==1){
  113.                                 String[] ss = StringUtils.split(t, "**", 2);
  114.                                 if (ss.length==2){
  115.                                         t = ss[0];
  116.                                 }
  117.                         }
  118.                         headerList.add(t);
  119.                 }
  120.                 initialize(title, headerList);
  121.         }
  122.         
  123.         /**
  124.          * 构造函数
  125.          * @param title 表格标题,传“空值”,表示无标题
  126.          * @param headers 表头数组
  127.          */
  128.         public ExportExcel(String title, String[] headers) {
  129.                 initialize(title, Lists.newArrayList(headers));
  130.         }
  131.         
  132.         /**
  133.          * 构造函数
  134.          * @param title 表格标题,传“空值”,表示无标题
  135.          * @param headerList 表头列表
  136.          */
  137.         public ExportExcel(String title, List<String> headerList) {
  138.                 initialize(title, headerList);
  139.         }
  140.         
  141.         /**
  142.          * 初始化函数
  143.          * @param title 表格标题,传“空值”,表示无标题
  144.          * @param headerList 表头列表
  145.          */
  146.         private void initialize(String title, List<String> headerList) {
  147.                 this.wb = new SXSSFWorkbook(500);
  148.                 this.sheet = wb.createSheet("Export");
  149.                 this.styles = createStyles(wb);
  150.                 // Create title
  151.                 if (StringUtils.isNotBlank(title)){
  152.                         Row titleRow = sheet.createRow(rownum++);
  153.                         titleRow.setHeightInPoints(30);
  154.                         Cell titleCell = titleRow.createCell(0);
  155.                         titleCell.setCellStyle(styles.get("title"));
  156.                         titleCell.setCellValue(title);
  157.                         sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(),
  158.                                         titleRow.getRowNum(), titleRow.getRowNum(), headerList.size()-1));
  159.                 }
  160.                 // Create header
  161.                 if (headerList == null){
  162.                         throw new RuntimeException("headerList not null!");
  163.                 }
  164.                 Row headerRow = sheet.createRow(rownum++);
  165.                 headerRow.setHeightInPoints(16);
  166.                 for (int i = 0; i < headerList.size(); i++) {
  167.                         Cell cell = headerRow.createCell(i);
  168.                         cell.setCellStyle(styles.get("header"));
  169.                         String[] ss = StringUtils.split(headerList.get(i), "**", 2);
  170.                         if (ss.length==2){
  171.                                 cell.setCellValue(ss[0]);
  172.                                 Comment comment = this.sheet.createDrawingPatriarch().createCellComment(
  173.                                                 new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
  174.                                 comment.setString(new XSSFRichTextString(ss[1]));
  175.                                 cell.setCellComment(comment);
  176.                         }else{
  177.                                 cell.setCellValue(headerList.get(i));
  178.                         }
  179.                         sheet.autoSizeColumn(i);
  180.                 }
  181.                 for (int i = 0; i < headerList.size(); i++) {  
  182.                         int colWidth = sheet.getColumnWidth(i)*2;
  183.                 sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);  
  184.                 }
  185.                 log.debug("Initialize success.");
  186.         }
  187.         
  188.         /**
  189.          * 创建表格样式
  190.          * @param wb 工作薄对象
  191.          * @return 样式列表
  192.          */
  193.         private Map<String, CellStyle> createStyles(Workbook wb) {
  194.                 Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  195.                
  196.                 CellStyle style = wb.createCellStyle();
  197.                 style.setAlignment(CellStyle.ALIGN_CENTER);
  198.                 style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
  199.                 Font titleFont = wb.createFont();
  200.                 titleFont.setFontName("Arial");
  201.                 titleFont.setFontHeightInPoints((short) 16);
  202.                 titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
  203.                 style.setFont(titleFont);
  204.                 styles.put("title", style);

  205.                 style = wb.createCellStyle();
  206.                 style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
  207.                 style.setBorderRight(CellStyle.BORDER_THIN);
  208.                 style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  209.                 style.setBorderLeft(CellStyle.BORDER_THIN);
  210.                 style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  211.                 style.setBorderTop(CellStyle.BORDER_THIN);
  212.                 style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  213.                 style.setBorderBottom(CellStyle.BORDER_THIN);
  214.                 style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  215.                 Font dataFont = wb.createFont();
  216.                 dataFont.setFontName("Arial");
  217.                 dataFont.setFontHeightInPoints((short) 10);
  218.                 style.setFont(dataFont);
  219.                 styles.put("data", style);
  220.                
  221.                 style = wb.createCellStyle();
  222.                 style.cloneStyleFrom(styles.get("data"));
  223.                 style.setAlignment(CellStyle.ALIGN_LEFT);
  224.                 styles.put("data1", style);

  225.                 style = wb.createCellStyle();
  226.                 style.cloneStyleFrom(styles.get("data"));
  227.                 style.setAlignment(CellStyle.ALIGN_CENTER);
  228.                 styles.put("data2", style);

  229.                 style = wb.createCellStyle();
  230.                 style.cloneStyleFrom(styles.get("data"));
  231.                 style.setAlignment(CellStyle.ALIGN_RIGHT);
  232.                 styles.put("data3", style);
  233.                
  234.                 style = wb.createCellStyle();
  235.                 style.cloneStyleFrom(styles.get("data"));
  236. //                style.setWrapText(true);
  237.                 style.setAlignment(CellStyle.ALIGN_CENTER);
  238.                 style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
  239.                 style.setFillPattern(CellStyle.SOLID_FOREGROUND);
  240.                 Font headerFont = wb.createFont();
  241.                 headerFont.setFontName("Arial");
  242.                 headerFont.setFontHeightInPoints((short) 10);
  243.                 headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
  244.                 headerFont.setColor(IndexedColors.WHITE.getIndex());
  245.                 style.setFont(headerFont);
  246.                 styles.put("header", style);
  247.                
  248.                 return styles;
  249.         }

  250.         /**
  251.          * 添加一行
  252.          * @return 行对象
  253.          */
  254.         public Row addRow(){
  255.                 return sheet.createRow(rownum++);
  256.         }
  257.         

  258.         /**
  259.          * 添加一个单元格
  260.          * @param row 添加的行
  261.          * @param column 添加列号
  262.          * @param val 添加值
  263.          * @return 单元格对象
  264.          */
  265.         public Cell addCell(Row row, int column, Object val){
  266.                 return this.addCell(row, column, val, 0, Class.class);
  267.         }
  268.         
  269.         /**
  270.          * 添加一个单元格
  271.          * @param row 添加的行
  272.          * @param column 添加列号
  273.          * @param val 添加值
  274.          * @param align 对齐方式(1:靠左;2:居中;3:靠右)
  275.          * @return 单元格对象
  276.          */
  277.         public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType){
  278.                 Cell cell = row.createCell(column);
  279.                 CellStyle style = styles.get("data"+(align>=1&&align<=3?align:""));
  280.                 try {
  281.                         if (val == null){
  282.                                 cell.setCellValue("");
  283.                         } else if (val instanceof String) {
  284.                                 cell.setCellValue((String) val);
  285.                         } else if (val instanceof Integer) {
  286.                                 cell.setCellValue((Integer) val);
  287.                         } else if (val instanceof Long) {
  288.                                 cell.setCellValue((Long) val);
  289.                         } else if (val instanceof Double) {
  290.                                 cell.setCellValue((Double) val);
  291.                         } else if (val instanceof Float) {
  292.                                 cell.setCellValue((Float) val);
  293.                         } else if (val instanceof Date) {
  294.                                 DataFormat format = wb.createDataFormat();
  295.                     style.setDataFormat(format.getFormat("yyyy-MM-dd"));
  296.                                 cell.setCellValue((Date) val);
  297.                         } else {
  298.                                 if (fieldType != Class.class){
  299.                                         cell.setCellValue((String)fieldType.getMethod("setValue", Object.class).invoke(null, val));
  300.                                 }else{
  301.                                         cell.setCellValue((String)Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
  302.                                                 "fieldtype."+val.getClass().getSimpleName()+"Type")).getMethod("setValue", Object.class).invoke(null, val));
  303.                                 }
  304.                         }
  305.                 } catch (Exception ex) {
  306.                         log.info("Set cell value ["+row.getRowNum()+","+column+"] error: " + ex.toString());
  307.                         cell.setCellValue(val.toString());
  308.                 }
  309.                 cell.setCellStyle(style);
  310.                 return cell;
  311.         }

  312.         /**
  313.          * 添加数据(通过annotation.ExportField添加数据)
  314.          * @return list 数据列表
  315.          */
  316.         public <E> ExportExcel setDataList(List<E> list){
  317.                 for (E e : list){
  318.                         int colunm = 0;
  319.                         Row row = this.addRow();
  320.                         StringBuilder sb = new StringBuilder();
  321.                         for (Object[] os : annotationList){
  322.                                 ExcelField ef = (ExcelField)os[0];
  323.                                 Object val = null;
  324.                                 // Get entity value
  325.                                 try{
  326.                                         if (StringUtils.isNotBlank(ef.value())){
  327.                                                 val = Reflections.invokeGetter(e, ef.value());
  328.                                         }else{
  329.                                                 if (os[1] instanceof Field){
  330.                                                         val = Reflections.invokeGetter(e, ((Field)os[1]).getName());
  331.                                                 }else if (os[1] instanceof Method){
  332.                                                         val = Reflections.invokeMethod(e, ((Method)os[1]).getName(), new Class[] {}, new Object[] {});
  333.                                                 }
  334.                                         }
  335.                                         // If is dict, get dict label
  336.                                         if (StringUtils.isNotBlank(ef.dictType())){
  337.                                                 val = DictUtils.getDictLabel(val==null?"":val.toString(), ef.dictType(), "");
  338.                                         }
  339.                                 }catch(Exception ex) {
  340.                                         // Failure to ignore
  341.                                         log.info(ex.toString());
  342.                                         val = "";
  343.                                 }
  344.                                 this.addCell(row, colunm++, val, ef.align(), ef.fieldType());
  345.                                 sb.append(val + ", ");
  346.                         }
  347.                         log.debug("Write success: ["+row.getRowNum()+"] "+sb.toString());
  348.                 }
  349.                 return this;
  350.         }
  351.         
  352.         /**
  353.          * 输出数据流
  354.          * @param os 输出数据流
  355.          */
  356.         public ExportExcel write(OutputStream os) throws IOException{
  357.                 wb.write(os);
  358.                 return this;
  359.         }
  360.         
  361.         /**
  362.          * 输出到客户端
  363.          * @param fileName 输出文件名
  364.          */
  365.         public ExportExcel write(HttpServletResponse response, String fileName) throws IOException{
  366.                 response.reset();
  367.         response.setContentType("application/octet-stream; charset=utf-8");
  368.         response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName));
  369.                 write(response.getOutputStream());
  370.                 return this;
  371.         }
  372.         
  373.         /**
  374.          * 输出到文件
  375.          * @param fileName 输出文件名
  376.          */
  377.         public ExportExcel writeFile(String name) throws FileNotFoundException, IOException{
  378.                 FileOutputStream os = new FileOutputStream(name);
  379.                 this.write(os);
  380.                 return this;
  381.         }
  382.         
  383.         /**
  384.          * 清理临时文件
  385.          */
  386.         public ExportExcel dispose(){
  387.                 wb.dispose();
  388.                 return this;
  389.         }
  390.         


  391. }
复制代码


捡代码论坛-最全的游戏源码下载技术网站! - 论坛版权郑重声明:
1、本主题所有言论和图片纯属会员个人意见,与本论坛立场无关
2、本站所有主题由该帖子作者发表,该帖子作者与捡代码论坛-最全的游戏源码下载技术网站!享有帖子相关版权
3、捡代码论坛版权,详细了解请点击。
4、本站所有内容均由互联网收集整理、网友上传,并且以计算机技术研究交流为目的,仅供大家参考、学习,不存在任何商业目的与商业用途。
5、若您需要商业运营或用于其他商业活动,请您购买正版授权并合法使用。 我们不承担任何技术及版权问题,且不对任何资源负法律责任。
6、如无法链接失效或侵犯版权,请给我们来信:jiandaima@foxmail.com

回复

使用道具 举报

*滑块验证:
您需要登录后才可以回帖 登录 | 立 即 注 册

本版积分规则

技术支持
在线咨询
QQ咨询
3351529868

QQ|手机版|小黑屋|捡代码论坛-专业源码分享下载 ( 陕ICP备15015195号-1|网站地图

GMT+8, 2025-2-22 16:40

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表