POI操作EXCEL

来源:互联网 发布:微信回调域名 编辑:程序博客网 时间:2024/06/03 20:44

http://blog.csdn.net/lovesomnus/article/details/23843549



认识POI

Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

结构:
HSSF - 提供读写Microsoft Excel格式档案的功能。
XSSF - 提供读写Microsoft Excel OOXML格式档案的功能。
HWPF - 提供读写Microsoft Word格式档案的功能。
HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
HDGF - 提供读写Microsoft Visio格式档案的功能。

在开源世界中,有两套比较有影响的API可 供开发者使用,一个是POI,一个是JXL,其中功能相对POI比较弱一点,所以我们日常开发中用到更多的往往是POI,在这里我们也只对POI做一个深入的使用讲解,并给出一个导Excel的工具类,适用任何列表的导出。


POI的jar包下载地址


简易的POI写入数据(认识API)


1:建立新HSSFWorkbook对象

        HSSFWorkbook  wb = new HSSFWorkbook();

2:建立新的sheet对象

         HSSFSheet  sheet  wb.createSheet("new sheet");

3:在sheet里创建一行,参数为行号

        HSSFRow r ow sheet.createRow((short)0);

4:在row里新建新cell(单元格)参数为列号

       4.1、给第一列设置一个整型值

                HSSFCell cell  =  row.createCell((short)0);

                cell.setCellValue(1);

       4.2、给第二列设置一个浮点型值

                HSSFCell  cell=  row.createCell((short)1);

                cell.setCellValue(1.2);

       4.3、给第三列设置一个字符串型值

         HSSFCell  cell =  row.createCell((short)2);

         cell.setCellValue(“test”);

4.4、给第四列设置一个布尔型值

         HSSFCell  cell  row.createCell((short)3);

         cell.setCellValue(true);

4.5、给第五列设置一个日期型值

              设立新的cell样式 :

                      HSSFCellStyle  cellStyle  =  wb.createCellStyle();

              设置cell样式为定制的日期格式:

                     cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("yyyy年MM月dd日"));

                     HSSFCell cell  =  row.createCell((short)4);

                     cell.setCellValue(new Date());

                     cell.setCellStyle(cellStyle);

5:往磁盘写入excel文件

               FileOutputStream os = new FileOutputStream("d:\\test.xls");
               wb.write(os);
               os.close();


单元格样式设定


HSSFCellStyle style = workbook.createCellStyle();

单元格的顔色有前景色和背景色。 

style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);

style.setFillBackgroundColor(HSSFColor.SKY_BLUE.index);

POI提供的颜色类:HSSFColor


设定顔色时,用这些子类的静态常量「index」作为参数。


如果这些顔色还不够你用的话,怎么设定自己想要的顔色呢

填充模式

指定填充模式的话,使用「HSSFCellStyle」类的「setFillPattern」方法。 

style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

值说明NO_FILLNo backgroundSOLID_FOREGROUNDSolidly filledFINE_DOTSSmall fine dotsALT_BARSWide dotsSPARSE_DOTSSparse dotsTHICK_HORZ_BANDSThick horizontal bandsTHICK_VERT_BANDSThick vertical bandsTHICK_BACKWARD_DIAGThick backward facing diagonalsTHICK_FORWARD_DIAGThick forward facing diagonalsBIG_SPOTSLarge spotsBRICKSBrick-like layoutTHIN_HORZ_BANDSThin horizontal bandsTHIN_VERT_BANDSThin vertical bandsTHIN_BACKWARD_DIAGThin backward diagonalTHIN_FORWARD_DIAGThin forward diagonalSQUARESSquaresDIAMONDSDiamonds

设定边框的样式

style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);

设定单元格内容位置

style.setAlignment(HSSFCellStyle.ALIGN_CENTER);



文字样式设定


HSSFFont font = workbook.createFont();

设定文字颜色
font.setColor(HSSFColor.VIOLET.index);

设置字体大小
font.setFontHeightInPoints((short) 12);

设置字体粗细度
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);


把字体应用到当前的样式
style.setFont(font);


一个通用的工具类

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. public class ExportExcelUtil<T>{  
  2.   
  3.     /** 
  4.      * 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上 
  5.      *  
  6.      * @param title 
  7.      *  
  8.      *            表格标题名 
  9.      *  
  10.      * @param headers 
  11.      *  
  12.      *            表格属性列名数组 
  13.      *  
  14.      * @param dataset 
  15.      *  
  16.      *            需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 
  17.      *            javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据) 
  18.      *  
  19.      * @param out 
  20.      *  
  21.      *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中 
  22.      *  
  23.      * @param pattern 
  24.      *  
  25.      *            如果有时间数据,设定输出格式。默认为"yyy-MM-dd" 
  26.      *  
  27.      */  
  28.   
  29.     @SuppressWarnings("unchecked")  
  30.     public byte[] exportExcel(String title, String[] headers,Collection<T> dataset, String pattern){  
  31.         // 声明一个工作薄  
  32.         HSSFWorkbook workbook = new HSSFWorkbook();  
  33.         HSSFFont font3 = workbook.createFont();  
  34.         // 生成一个表格  
  35.         // 生成一个样式  
  36.         HSSFCellStyle style = workbook.createCellStyle();  
  37.         // 设置这些样式  
  38.         style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);  
  39.         style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
  40.         style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  41.         style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  42.         style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  43.         style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  44.         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  45.         // 生成一个字体  
  46.         HSSFFont font = workbook.createFont();  
  47.         font.setColor(HSSFColor.VIOLET.index);  
  48.         font.setFontHeightInPoints((short12);  
  49.         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  50.         // 把字体应用到当前的样式  
  51.         style.setFont(font);  
  52.         // 生成并设置另一个样式  
  53.         HSSFCellStyle style2 = workbook.createCellStyle();  
  54.         style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);  
  55.         style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
  56.         style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  57.         style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  58.         style2.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  59.         style2.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  60.         style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  61.         style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  62.         // 生成另一个字体  
  63.         HSSFFont font2 = workbook.createFont();  
  64.         font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);  
  65.         // 把字体应用到当前的样式  
  66.         style2.setFont(font2);  
  67.         HSSFSheet sheet = null;  
  68.         HSSFRow row = null;  
  69.         int index = 0;  
  70.         int sheetnum = 0;  
  71.         Iterator<T> it = dataset.iterator();  
  72.         // 产生表格标题行  
  73.         sheet = workbook.createSheet(title + sheetnum);  
  74.         sheet.setDefaultColumnWidth((short15);  
  75.         row = sheet.createRow(0);  
  76.         for (short i = 0; i < headers.length; i++){  
  77.             HSSFCell cell = row.createCell(i);  
  78.             cell.setCellStyle(style);  
  79.             HSSFRichTextString text = new HSSFRichTextString(headers[i]);  
  80.             cell.setCellValue(text);  
  81.         }  
  82.         while (it.hasNext()){  
  83.             index++;  
  84.             if (index > 50000){  
  85.                 index = 0;  
  86.                 ++sheetnum;  
  87.                 sheet = workbook.createSheet(title + sheetnum);  
  88.                 sheet.setDefaultColumnWidth((short15);  
  89.                 row = sheet.createRow(0);  
  90.                 for (short i = 0; i < headers.length; i++){  
  91.                     HSSFCell cell = row.createCell(i);  
  92.                     cell.setCellStyle(style);  
  93.                     HSSFRichTextString text = new HSSFRichTextString(headers[i]);  
  94.                     cell.setCellValue(text);  
  95.                 }  
  96.             }  
  97.             row = sheet.createRow(index);  
  98.             T t = (T) it.next();  
  99.             // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值  
  100.             Field[] fields = t.getClass().getDeclaredFields();  
  101.             for (short i = 0; i < fields.length; i++){  
  102.                 HSSFCell cell = row.createCell(i);  
  103.                 cell.setCellStyle(style2);  
  104.                 Field field = fields[i];  
  105.                 String fieldName = field.getName();  
  106.                 String getMethodName = "get"+ fieldName.substring(01).toUpperCase()+ fieldName.substring(1);  
  107.                 try{  
  108.                     Class tCls = t.getClass();  
  109.                     Method getMethod = tCls.getMethod(getMethodName,new Class[] {});  
  110.                     Object value = getMethod.invoke(t, new Object[] {});  
  111.                     // 判断值的类型后进行强制类型转换  
  112.                     String textValue = null;  
  113.                     if (value instanceof Integer){  
  114.                         int intValue = (Integer) value;  
  115.                         cell.setCellValue(intValue);  
  116.                     }  
  117.                     else if (value instanceof Float){  
  118.                         float fValue = (Float) value;  
  119.                         textValue = new HSSFRichTextString(String.valueOf(fValue)).toString();  
  120.                         cell.setCellValue(textValue);  
  121.                     }  
  122.                     else if (value instanceof Double){  
  123.                         double dValue = (Double) value;  
  124.                         textValue = new HSSFRichTextString(String.valueOf(dValue)).toString();  
  125.                         cell.setCellValue(textValue);  
  126.                     }  
  127.                     else if (value instanceof Long){  
  128.                         long longValue = (Long) value;  
  129.                         cell.setCellValue(longValue);  
  130.                     }  
  131.                     if (value instanceof Boolean){  
  132.                         boolean bValue = (Boolean) value;  
  133.                         textValue = "true";  
  134.                         if (!bValue){  
  135.                             textValue = "false";  
  136.                         }  
  137.                     }  
  138.                     else if (value instanceof Date){  
  139.                         Date date = (Date) value;  
  140.                         if ("".equals(pattern)){  
  141.                             pattern = "yyy-MM-dd";  
  142.                         }  
  143.                         SimpleDateFormat sdf = new SimpleDateFormat(pattern);  
  144.                         textValue = sdf.format(date);  
  145.                     }  
  146.                     else{  
  147.                         if (null == value || "".equals(value)){  
  148.                             value = "";  
  149.                         }  
  150.                         else{  
  151.                             textValue = value.toString();  
  152.                         }  
  153.                     }  
  154.                     // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成  
  155.                     if (textValue != null){  
  156.                         Pattern p = Pattern.compile("^//d+(//.//d+)?$");  
  157.                         Matcher matcher = p.matcher(textValue);  
  158.                         if (matcher.matches()){  
  159.                             // 是数字当作double处理  
  160.                             cell.setCellValue(Double.parseDouble(textValue));  
  161.                         }  
  162.                         else{  
  163.                             HSSFRichTextString richString = new HSSFRichTextString(textValue);  
  164.                             font3.setColor(HSSFColor.BLUE.index);  
  165.                             richString.applyFont(font3);  
  166.                             cell.setCellValue(richString);  
  167.                         }  
  168.                     }  
  169.                 }  
  170.                 catch (Exception e){  
  171.                     e.printStackTrace();  
  172.                 }  
  173.             }  
  174.         }  
  175.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  176.         try{  
  177.             workbook.write(baos);  
  178.             baos.flush();  
  179.         }  
  180.         catch (IOException e){  
  181.             e.printStackTrace();  
  182.         }  
  183.         return baos.toByteArray();  
  184.     }  
  185. }  

导出的excel样例


0 0
原创粉丝点击