zoukankan      html  css  js  c++  java
  • java poi导出Excel 总结

    首先下载 Apache 的POI jar包

    将更目录下的poi-3.8-20120326.jar 和lib下的三个jar包导入 如下图:

    首先必须搞一个通用的工具类,网上找的,能用就行,java就是这么高效率

    ExcelUtil类:

      1 package cn.xujingyang.util;
      2 
      3 import java.lang.reflect.Method ;
      4 import java.text.SimpleDateFormat ;
      5 import java.util.Collection ;
      6 import java.util.Date ;
      7 import java.util.Iterator ;
      8 import java.util.Map ;
      9 import java.util.regex.Matcher ;
     10 import java.util.regex.Pattern ;
     11 import org.apache.poi.hssf.usermodel.HSSFCell ;
     12 import org.apache.poi.hssf.usermodel.HSSFCellStyle ;
     13 import org.apache.poi.hssf.usermodel.HSSFClientAnchor ;
     14 import org.apache.poi.hssf.usermodel.HSSFFont ;
     15 import org.apache.poi.hssf.usermodel.HSSFPatriarch ;
     16 import org.apache.poi.hssf.usermodel.HSSFRichTextString ;
     17 import org.apache.poi.hssf.usermodel.HSSFRow ;
     18 import org.apache.poi.hssf.usermodel.HSSFSheet ;
     19 import org.apache.poi.hssf.usermodel.HSSFWorkbook ;
     20 import org.apache.poi.hssf.util.HSSFColor ;
     21 
     22 public class ExcelUtil<T> {
     23      /** 
     24      *  
     25      * @param title 
     26      *            表格标题名 
     27      * @param headers 
     28      *            表格属性列名数组 (第一行标题)
     29      * @param Col 
     30      *            需要显示的表格属性列名数组 如果是javabean 必须和字段名字一直 如果为Map 必须为Map的key名字对应
     31      * @param dataset 
     32      *            需要显示的数据集合,集合泛型支持两种,1:符合javabean风格的类的对象 2:Map类型。此方法支持的 
     33      *            javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据) 
     34      * @param pattern 
     35      *            如果有时间数据,设定输出格式。默认为"yyy-MM-dd" 
     36      */  
     37     public HSSFWorkbook exportExcel(String title, String[] headers,String[] Col,Collection<T> dataset, String pattern) {
     38         if(pattern == null || pattern.equals("")) pattern = "yyy-MM-dd";
     39         // 声明一个工作薄
     40         HSSFWorkbook workbook = new HSSFWorkbook();
     41         // 生成一个表格
     42         HSSFSheet sheet = workbook.createSheet(title);
     43         // 设置表格默认列宽度为15个字节
     44         sheet.setDefaultColumnWidth(15);
     45         // 生成一个样式
     46         HSSFCellStyle style = workbook.createCellStyle();
     47         // 设置这些样式
     48         style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
     49         style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
     50         style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
     51         style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
     52         style.setBorderRight(HSSFCellStyle.BORDER_THIN);
     53         style.setBorderTop(HSSFCellStyle.BORDER_THIN);
     54         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
     55         // 生成一个字体
     56         HSSFFont font = workbook.createFont();
     57         font.setColor(HSSFColor.VIOLET.index);
     58         font.setFontHeightInPoints((short) 12);
     59         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
     60         // 把字体应用到当前的样式
     61         style.setFont(font);
     62         // 生成并设置另一个样式
     63         HSSFCellStyle style2 = workbook.createCellStyle();
     64         style2.setFillForegroundColor(HSSFColor.WHITE.index);
     65         style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
     66         style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
     67         style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
     68         style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
     69         style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
     70         style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
     71         style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
     72         // 生成另一个字体
     73         HSSFFont font2 = workbook.createFont();
     74         font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
     75         // 把字体应用到当前的样式
     76         style2.setFont(font2);
     77         // 声明一个画图的顶级管理器
     78         HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
     79         // 产生表格标题行
     80         HSSFRow row = sheet.createRow(0);
     81         int Cell = 0;
     82         for (short i = 0; i < headers.length; i++) {
     83             HSSFCell cell = row.createCell(Cell);
     84             cell.setCellStyle(style);
     85             HSSFRichTextString text = new HSSFRichTextString(headers[i]);
     86             cell.setCellValue(text);
     87             Cell ++ ;
     88         }
     89         // 遍历集合数据,产生数据行
     90         Iterator<T> it = dataset.iterator();
     91         int index = 0;
     92         while (it.hasNext()) {
     93             index++;
     94             row = sheet.createRow(index);
     95             T t = (T) it.next();
     96             String[] fields = Col;
     97             Cell = 0;
     98             for (short i = 0; i < fields.length; i++) {
     99                 String fieldName = fields[i];
    100                 HSSFCell cell = row.createCell(Cell);
    101                 cell.setCellStyle(style2);
    102                 try {
    103                     Object value = "";
    104                     Class tCls = null;
    105                     Map map = null;
    106                     if(t instanceof Map){
    107                         map = (Map)t;
    108                         value = map.get(fieldName);
    109                     } else {
    110                         String getMethodName = "get"
    111                                 + fieldName.substring(0, 1).toUpperCase()
    112                                 + fieldName.substring(1);
    113                         tCls = t.getClass();
    114                         Method getMethod = tCls.getMethod(getMethodName,new Class[] {});
    115                         value = getMethod.invoke(t, new Object[] {});
    116                     }
    117                     if(value == null ) value = "";
    118                     // 判断值的类型后进行强制类型转换
    119                     String textValue = null;
    120                     if (value instanceof Date) {
    121                         Date date = (Date) value;
    122                         SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    123                         textValue = sdf.format(date);
    124                     } else if (value instanceof byte[]) {
    125                         // 有图片时,设置行高为60px;
    126                         row.setHeightInPoints(60);
    127                         // 设置图片所在列宽度为80px,注意这里单位的一个换算
    128                         sheet.setColumnWidth(Cell, (short) (35.7 * 80));
    129                         // sheet.autoSizeColumn(i);
    130                         byte[] bsValue = (byte[]) value;
    131                         HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
    132                                 1023, 255, (short) 6, index, (short) 6, index);
    133                         anchor.setAnchorType(2);
    134                         patriarch.createPicture(anchor, workbook.addPicture(
    135                                 bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
    136                     } else {
    137                         // 其它数据类型都当作字符串简单处理
    138                         textValue = value.toString();
    139                     }
    140                     // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
    141                     if (textValue != null) {
    142                         Pattern p = Pattern.compile("^//d+(//.//d+)?$");
    143                         Matcher matcher = p.matcher(textValue);
    144                         if (matcher.matches()) {
    145                             // 是数字当作double处理
    146                             cell.setCellValue(Double.parseDouble(textValue));
    147                         } else {
    148                             HSSFRichTextString richString = new HSSFRichTextString(
    149                                     textValue);
    150                             HSSFFont font3 = workbook.createFont();
    151                             font3.setColor(HSSFColor.BLUE.index);
    152                             richString.applyFont(font3);
    153                             cell.setCellValue(richString);
    154                         }
    155                     }
    156                     Cell ++ ;
    157                 } catch (Exception e) {
    158                     e.printStackTrace();
    159                 }
    160             }
    161         }
    162         return workbook;
    163     }
    164 }

    测试例子:

     1 .....
     2 
     3 String [] headers = null ;
     4         String [] Col = null ;
     5         List excelList = null ;
     6         ExcelUtil<LoginlogNumVO> ex = new ExcelUtil<LoginlogNumVO>() ;
     7        18         // 表头
    19         headers = new String [] { "操作日期","用户编码", "用户名称", "IP地址","端口号","登录状态","进入模块","登录入口" } ;
    20         // 数据键名或者MODEL类字段名
    21         Col = new String [] { "date","u_code", "u_name", "ip","port","satus","module","enter" } ;
    22             
    23         // 这是model类型的数据 写的例子 暂时不添加数据
    24         excelList = loginLogService.getListByPage(0, loginLogService
    25                     .getRowCount(key, keywords, dateStart, dateEnd, enter), key,
    26                     keywords, dateStart, dateEnd, enter) ;
    27 28         
    29         // 生成Excel
    30         HSSFWorkbook workbook = ex.exportExcel("sheet1", headers, Col, excelList, null) ;
    31         // 下载
    32         response.setContentType("application/vnd.ms-excel;charset=UTF-8") ;
    33         response.setHeader("Content-disposition",
    34                 "attachment;filename=" + System.currentTimeMillis() + "_login_log_sheet.xls") ;
    35         OutputStream ouputStream ;
    36         try {
    37             ouputStream = response.getOutputStream() ;
    38             workbook.write(ouputStream) ;
    39             ouputStream.flush() ;
    40             ouputStream.close() ;
    41         } catch (IOException e) {
    42             e.printStackTrace() ;
    43         }
    44 
    45 .....

    挺简单~~~

  • 相关阅读:
    redis如何实现数据同步
    mysql调优学习笔记
    介绍一个好用的dao层与mybatis互跳的idea插件MyBatisCodeHelperPro
    springboot执行流程
    zookeeper
    (原创) cocos2dx使用Curl连接网络(客户端)
    (转) Eclipse连接MySQL数据库(傻瓜篇)
    (原创)cocos2dx使用jsoncpp的正确姿势
    Java web开发(17)SpirngMVC 详解
    PLC 程序和仿真
  • 原文地址:https://www.cnblogs.com/xujingyang/p/6832849.html
Copyright © 2011-2022 走看看