[Java] java导出Excel格式文件 →→→→→进入此内容的聊天室

来自 , 2019-10-03, 写在 Java, 查看 117 次.
URL http://www.code666.cn/view/5d616dd3
  1. import java.io.ByteArrayInputStream;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.InputStream;
  4. import java.io.UnsupportedEncodingException;
  5. import java.lang.reflect.Array;
  6. import java.lang.reflect.InvocationTargetException;
  7. import java.lang.reflect.Method;
  8. import java.text.SimpleDateFormat;
  9. import java.util.List;
  10. import java.util.regex.Matcher;
  11. import java.util.regex.Pattern;
  12.  
  13. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  14. import org.apache.poi.ss.usermodel.Cell;
  15. import org.apache.poi.ss.usermodel.CellStyle;
  16. import org.apache.poi.ss.usermodel.Font;
  17. import org.apache.poi.ss.usermodel.IndexedColors;
  18. import org.apache.poi.ss.usermodel.Row;
  19. import org.apache.poi.ss.usermodel.Sheet;
  20. import org.apache.poi.ss.usermodel.Workbook;
  21.  
  22. import com.gzbugu.action.ActionBase;
  23. import com.gzbugu.domain.BusiObservePlan;
  24.  
  25. /**
  26.  * @author ylh
  27.  */
  28. public class ExcelAction extends ActionBase{
  29.  
  30.     private List downExcelAttrsList;
  31.     private String fileName;
  32.  
  33.     /**
  34.      * 导出Excel公共方法
  35.      * 使用action模板配置文件:
  36.         <action name="自定义" class="自定义" method="自定义">
  37.             <result name="success" type="chain">
  38.                 <param name="actionName">getDownloadExcel</param>  
  39.                 <param name="downExcelAttrsList">${downExcelAttrsList}</param>  
  40.             </result>
  41.         </action>
  42.      * 必须的参数downExcelAttrsList,必须是有setter,getter方法的属性,其包括参数顺序如下:
  43.      * @param valueList   必须,通过hql查询数据库后返回的对象List,支持关联查询,在属性前加上对象名: {"BusiObservePlan.planType,0:个人计划,1:部门月度计划",...}
  44.      * @param sheetName  必须,Excel的sheet的名字,
  45.      * @param beanPropertyNames 必须,对象中需要被输出的值,如果是状态值需要被替换的,则如此填写:   {"propertyName,0:个人计划,1:部门月度计划", ...}
  46.      * @param titleNames 必须,对应上面属性的名字,用来做Excel的表头
  47.      * @param fileName     可选,生成的excel名称,如果没有,则默认是sheetName
  48.      */
  49.     public InputStream getDownloadExcel(){
  50.         final List list = (List)downExcelAttrsList.get(0);
  51.         final String sheetName = (String)downExcelAttrsList.get(1);
  52.         final String[] beanPropertyNames = (String[])downExcelAttrsList.get(2);
  53.         final String[] titleNames = (String[])downExcelAttrsList.get(3);
  54.         if(downExcelAttrsList.size()>=5) {
  55.             fileName = (String)downExcelAttrsList.get(4);
  56.         }else{
  57.             fileName = sheetName;
  58.         }
  59.         if(!fileName.contains(".xls")){
  60.             fileName = fileName + ".xls";
  61.         }
  62.         InputStream is = null;
  63.         try {
  64.             is = this.createExcelFile(list, sheetName, beanPropertyNames, titleNames);
  65.         } catch (Exception e1) {
  66.             e1.printStackTrace();
  67.         }
  68.         try {
  69.             fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
  70.         } catch (UnsupportedEncodingException e) {
  71.             e.printStackTrace();
  72.         }
  73.         if(null==is) System.out.print("shit...");
  74.         return is;
  75.     }
  76.  
  77.     /**
  78.      * 生成Excel表
  79.      */
  80.     private InputStream createExcelFile(List valueList, String sheetName, String[] beanPropertyNames, String[] titleNames) throws Exception{
  81.         Workbook wb = new HSSFWorkbook();
  82.         Sheet sheet = wb.createSheet(sheetName);
  83.         //单元格默认宽度为20
  84.         sheet.setDefaultColumnWidth(20);
  85.         Cell cell;
  86.  
  87.         //表头
  88.         Row headerRow = sheet.createRow(0);
  89.         headerRow.setHeightInPoints(18f);
  90.         for (int i = 0; i < titleNames.length; i++) {
  91.             cell = headerRow.createCell(i);
  92.             cell.setCellValue(titleNames[i]);
  93.             cell.setCellStyle(this.getHeaderCellStyle(wb));
  94.         }
  95.  
  96.         //freeze the first row
  97.         sheet.createFreezePane(0, 1);
  98.  
  99.         Row row;
  100.         int rownum = 1, listSize = valueList.size(), beanPropertyNamesLength = beanPropertyNames.length;
  101.         for (int i = 0; i < listSize; i++, rownum++) {
  102.             row = sheet.createRow(rownum);
  103.             Object currentObj = valueList.get(i);
  104.             for ( int j=0; j < beanPropertyNamesLength; j++ ) {
  105.                 cell = row.createCell(j);
  106.                 cell.setCellStyle(this.getContentCellStyle(wb));
  107.                 Object value = this.getPropertyValue(currentObj, beanPropertyNames[j]);
  108.                 this.getCellSetValue(cell, value);
  109.             }
  110.         }
  111.  
  112.         //将输出流转化为输入流
  113.         wb.write(out);
  114.         return new ByteArrayInputStream(out.toByteArray());
  115.     }  
  116.  
  117.     /**
  118.      * 设置单元格值
  119.      * @param cell
  120.      * @param value
  121.      */
  122.     private void getCellSetValue(Cell cell, Object value){
  123.         String type = value.getClass().toString().toLowerCase();
  124.         if(type.endsWith("integer")){
  125.             cell.setCellValue((Integer)value);
  126.         }else if(type.endsWith("double")){
  127.             cell.setCellValue((Double)value);
  128.         }else if(type.endsWith("timestamp")){
  129.             cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(value).toString());
  130.         }else{
  131.             String val = (String)value;
  132.             Pattern pattern = Pattern.compile("<\\w*\\s*/?>");
  133.             Matcher matcher = pattern.matcher(val);
  134.             String v = matcher.replaceAll("");
  135.             //将结束符号替换为:。
  136.             pattern = Pattern.compile("</\\w*\\s*/?>");
  137.             matcher = pattern.matcher(v);
  138.             v = matcher.replaceAll("。");
  139.             cell.setCellValue(v);
  140.         }      
  141.     }
  142.  
  143.     /**
  144.      * 获得bean对象中对应属性的值
  145.      * @param obj
  146.      * @param propertyName
  147.      * @return
  148.      */
  149.     private Object getPropertyValue(Object obj,String beanPropertyName){
  150.         final String[] property = beanPropertyName.split(",");
  151.         final String[] beanNameAndPropertyName = property[0].split("\\.");
  152.         final String beanName = beanNameAndPropertyName[0].toLowerCase();
  153.         final String propertyName = beanNameAndPropertyName[1];
  154.         Object value = "";
  155.         Method met = null;
  156.  
  157.         //关联查询
  158.         if(obj.getClass().isArray()){
  159.             int objLength = Array.getLength(obj);
  160.             Object[] currentObjectArray = (Object[])obj;
  161.             for(int j=0;j<objLength;j++){
  162.                 Object currentObject = currentObjectArray[j];                  
  163.                 String currentObjectBeanName = currentObject.getClass().getSimpleName().toLowerCase();
  164.                 if(currentObjectBeanName.equals(beanName)){
  165.                     try {
  166.                         met = currentObject.getClass().getMethod(this.getterMethodName(propertyName));
  167.                     } catch (SecurityException e) {
  168.                         e.printStackTrace();
  169.                     } catch (NoSuchMethodException e) {
  170.                         e.printStackTrace();
  171.                     }
  172.                     try {
  173.                         value = met.invoke(currentObject);
  174.                     } catch (IllegalArgumentException e) {
  175.                         e.printStackTrace();
  176.                     } catch (IllegalAccessException e) {
  177.                         e.printStackTrace();
  178.                     } catch (InvocationTargetException e) {
  179.                         e.printStackTrace();
  180.                     }
  181.                 }
  182.             }                
  183.         }else{
  184.             //属性的形式为:   对象.属性  
  185.             if(beanNameAndPropertyName.length>1){
  186.                 try {
  187.                     met = obj.getClass().getMethod(this.getterMethodName(propertyName));
  188.                 } catch (SecurityException e1) {
  189.                     e1.printStackTrace();
  190.                 } catch (NoSuchMethodException e1) {
  191.                     e1.printStackTrace();
  192.                 }
  193.                 try {
  194.                     value = met.invoke(obj);
  195.                 } catch (IllegalArgumentException e) {
  196.                     e.printStackTrace();
  197.                 } catch (IllegalAccessException e) {
  198.                     e.printStackTrace();
  199.                 } catch (InvocationTargetException e) {
  200.                     e.printStackTrace();
  201.                 }
  202.             }else{
  203.                 //属性的形式为:   属性
  204.                 try {
  205.                     met = obj.getClass().getMethod(this.getterMethodName(property[0]));
  206.                 } catch (SecurityException e) {
  207.                     e.printStackTrace();
  208.                 } catch (NoSuchMethodException e) {
  209.                     e.printStackTrace();
  210.                 }  
  211.                 try {
  212.                     value = met.invoke(obj);
  213.                 } catch (IllegalArgumentException e) {
  214.                     e.printStackTrace();
  215.                 } catch (IllegalAccessException e) {
  216.                     e.printStackTrace();
  217.                 } catch (InvocationTargetException e) {
  218.                     e.printStackTrace();
  219.                 }
  220.             }                
  221.         }
  222.  
  223.         //状态值替换
  224.         if(property.length>1){
  225.             value = this.replaceValue(property, value);
  226.         }
  227.  
  228.         return value;
  229.     }
  230.  
  231.     /**
  232.      * 根据内容来替换对应的状态值
  233.      * @param propertyContent
  234.      * @param value
  235.      * @return
  236.      */
  237.     private Object replaceValue(String[] propertyContent, Object value){
  238.         int len = propertyContent.length;
  239.         String name = value.getClass().getSimpleName().toLowerCase();
  240.         for(int i=1;i<len;i++){
  241.             String[] statusValueAndReplaceValue = propertyContent[i].split(":");
  242.             if("integer".equals(name)&&Integer.parseInt(statusValueAndReplaceValue[0])==(Integer)value){
  243.                 value = statusValueAndReplaceValue[1];
  244.                 break;
  245.             }
  246.         }
  247.         return value;
  248.     }
  249.  
  250.     /**
  251.      * 根据属性名字获得对应的bean对象的getter名字
  252.      * @param beanPropertyName  bean对象的属性名字
  253.      * @return
  254.      */
  255.     private String getterMethodName(String beanPropertyName){
  256.         String name = "get"+beanPropertyName.substring(0, 1).toUpperCase()+beanPropertyName.substring(1);
  257.         return name;
  258.     }
  259.  
  260.     /**
  261.      * 表头样式
  262.      * @param wb
  263.      * @return
  264.      */
  265.     private CellStyle getHeaderCellStyle(Workbook wb){
  266.         Font headerFont = wb.createFont();
  267.         headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
  268.         CellStyle style = createBorderedStyle(wb);
  269.         style.setAlignment(CellStyle.ALIGN_CENTER);
  270.         style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
  271.         style.setFillPattern(CellStyle.SOLID_FOREGROUND);
  272.         style.setFont(headerFont);
  273.         return style;
  274.     }
  275.  
  276.     /**
  277.      * 单元格边框样式
  278.      * @param wb
  279.      * @return
  280.      */
  281.     private CellStyle createBorderedStyle(Workbook wb){
  282.         CellStyle style = wb.createCellStyle();
  283.         style.setBorderRight(CellStyle.BORDER_THIN);
  284.         style.setRightBorderColor(IndexedColors.BLACK.getIndex());
  285.         style.setBorderBottom(CellStyle.BORDER_THIN);
  286.         style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
  287.         style.setBorderLeft(CellStyle.BORDER_THIN);
  288.         style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
  289.         style.setBorderTop(CellStyle.BORDER_THIN);
  290.         style.setTopBorderColor(IndexedColors.BLACK.getIndex());
  291.         return style;
  292.     }
  293.  
  294.     /**
  295.      * 内容部分单元格样式
  296.      * @param wb
  297.      * @return
  298.      */
  299.     private CellStyle getContentCellStyle(Workbook wb){
  300.         CellStyle style = createBorderedStyle(wb);
  301.         style.setAlignment(CellStyle.ALIGN_CENTER);
  302.         return style;
  303.     }
  304.  
  305.     public List getDownExcelAttrsList() {
  306.         return downExcelAttrsList;
  307.     }
  308.  
  309.     public void setDownExcelAttrsList(List downExcelAttrsList) {
  310.         this.downExcelAttrsList = downExcelAttrsList;
  311.     }
  312.  
  313.     public String getFileName() {
  314.         return fileName;
  315.     }
  316.  
  317.     public void setFileName(String fileName) {
  318.         this.fileName = fileName;
  319.     }
  320. }
  321.  
  322. //源代码片段来自云代码http://yuncode.net
  323.                        

回复 " java导出Excel格式文件"

这儿你可以回复上面这条便签

captcha