一般Excel导出功能

public class ExcelUtil {
    
    /**
     *
     * @param dataList 数据列表
     * @param headers 表头
     * @param os 输出流
     */
    public static void commonExport(List<List<String>> dataList, String title, String[] headers, OutputStream os) {
        try {
            // 声明一个工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 生成一个表格
            HSSFSheet sheet = workbook.createSheet(title);
            // 设置表格默认列宽度为15个字节
            sheet.setDefaultColumnWidth(15);
            // 生成一个样式
            HSSFCellStyle style = workbook.createCellStyle();
            style.setFillForegroundColor(HSSFColor.WHITE.index);
            style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            style.setBorderRight(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.BLACK.index);
            font.setFontHeightInPoints((short)12);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            
            // 字体应用到当前样式
            style.setFont(font);
            
            // 设置并生成另一个样式
            HSSFCellStyle style2 = workbook.createCellStyle();
            style2.setFillForegroundColor(HSSFColor.WHITE.index);
            style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
            style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
            style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            
            // 生成另一个字体
            HSSFFont font2 = workbook.createFont();
            font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
            style2.setFont(font2);
            
            // 声明一个画图的顶级管理器
            HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
            // 定义注释大小和位置
            HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,0,0,0,(short)4,2,(short)6,5));
            // 设置注释内容
            comment.setString(new HSSFRichTextString("可以在POI中添加注释"));
            // 设置注释作者
            comment.setAuthor("leno");
            
            if (null == headers) {
                headers = new String[0];
            }
            // 产生表格标题行
            HSSFRow row = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(style);
                HSSFRichTextString text = new HSSFRichTextString(headers[i]);
                cell.setCellValue(text);
            }
            
            if (null == dataList) {
                dataList = new ArrayList<List<String>>();
            }
            for (int i = 0; i < dataList.size(); i++) {
                List<String> data = dataList.get(i);
                row = sheet.createRow((i + 1));
                
                for (int j = 0; j < data.size(); j++) {
                    HSSFCell cell = row.createCell(j);
                    cell.setCellStyle(style2);
                    String textValue = data.get(j);
                    
                    Pattern p = Pattern.compile("^//d+(//.//d+)?$");  
                    Matcher matcher = p.matcher(textValue);
                    if(matcher.matches()){
                        //是数字当作double处理
                        cell.setCellValue(Double.parseDouble(textValue));
                     } else {
                         HSSFRichTextString richString = new HSSFRichTextString(textValue);
                         HSSFFont font3 = workbook.createFont();
                         font3.setColor(HSSFColor.BLACK.index);
                         richString.applyFont(font3);
                         cell.setCellValue(richString);
                     }
                }
            }
            workbook.write(os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.flush();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }

    /**
     *
     * @param dataList 数据列表
     * @param headers 表头
     * @param os 输出流
     */
    public static void collectExport(List<List<String>> dataList, String title, String[] headers, OutputStream os) {
        try {
            // 声明一个工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 生成一个表格
            HSSFSheet sheet = workbook.createSheet(title);
            // 设置表格默认列宽度为30个字节
            sheet.setDefaultColumnWidth(30);
            
            // 生成一个样式
            HSSFCellStyle style = workbook.createCellStyle();
            style.setFillForegroundColor(HSSFColor.WHITE.index);
            style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            style.setBorderRight(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.BLACK.index);
            font.setFontHeightInPoints((short)12);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            
            // 字体应用到当前样式
            style.setFont(font);
            
            // 设置并生成另一个样式(正文样式)
            HSSFCellStyle style2 = workbook.createCellStyle();
            style2.setWrapText(true);
            style2.setLocked(false);
            style2.setFillForegroundColor(HSSFColor.WHITE.index);
            style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
            style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
            style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            
            // 生成另一个字体(正文字体)
            HSSFFont font2 = workbook.createFont();
            font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
            style2.setFont(font2);
            
            if (null == headers) {
                headers = new String[0];
            }
            
            HSSFRow row1 = sheet.createRow(0);
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length - 2));
            HSSFCell cel1 = row1.createCell(0);
            cel1.setCellStyle(style);
            cel1.setCellValue(title);
            
            // 产生表格标题行
            HSSFRow row = sheet.createRow(1);
            for (int i = 0; i < headers.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(style);
                HSSFRichTextString text = new HSSFRichTextString(headers[i]);
                cell.setCellValue(text);
            }
            
            if (null == dataList) {
                dataList = new ArrayList<List<String>>();
            }
            for (int i = 0; i < dataList.size(); i++) {
                List<String> data = dataList.get(i);
                row = sheet.createRow((i + 2));
                
                for (int j = 0; j < data.size(); j++) {
                    HSSFCell cell = row.createCell(j);
                    cell.setCellStyle(style2);
                    String textValue = data.get(j);
                    
                    Pattern p = Pattern.compile("^//d+(//.//d+)?$");  
                    Matcher matcher = p.matcher(textValue);
                    if(matcher.matches()){
                        //是数字当作double处理
                        cell.setCellValue(Double.parseDouble(textValue));
                     } else {
                         HSSFRichTextString richString = new HSSFRichTextString(textValue);
                         HSSFFont font3 = workbook.createFont();
                         font3.setColor(HSSFColor.BLACK.index);
                         richString.applyFont(font3);
                         cell.setCellValue(richString);
                     }
                }
            }
            workbook.write(os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.flush();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }

    /**
     * 从对象中取出展示的值
     * @param fieldNames
     * @param list
     * @param cls
     * @return
     */
    public static List<List<String>> transObjToString(String[] fieldNames, List<Object> list, Class<?> cls){
        if (null == list || list.size() == 0) {
            return null;
        }
        List<List<String>> dataList = new ArrayList<List<String>>();
        for (int j = 0; j < list.size(); j++) {
            Object gbm = list.get(j);
            List<String> data = new ArrayList<String>();
            for (int i = 0; i < fieldNames.length; i++) {
                try {
                    String fieldName = fieldNames[i];
                    String value = getValues(gbm, fieldName, cls);
                    data.add(value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            dataList.add(data);
        }
        return dataList;
    }
    
    /**
     * 获取对象的特定值
     * @param gbm
     * @param fieldName
     * @param cls
     * @return
     * @throws Exception
     */
    private static String getValues(Object gbm, String fieldName, Class<?> cls) throws Exception{
        String returnValue = "";
        try {
            PropertyDescriptor pd = new PropertyDescriptor(fieldName, cls);
            Method getMethod = pd.getReadMethod();//获得get方法
            Object o = getMethod.invoke(gbm);//执行get方法返回一个Object
            if (null != o && o instanceof Date) {
                returnValue = DateUtil.convertDateToString((Date)o, "yyyy-MM-dd");
            }
            if (null != o && o instanceof SysOrgPerson) {
                returnValue = ((SysOrgPerson)o).getFdName();
            }
            if (null != o && o instanceof SysOrgElement) {
                returnValue = ((SysOrgElement)o).getFdName();
            }
            if (o != null && o instanceof org.hibernate.collection.PersistentBag) {
                PersistentBag temp = (PersistentBag) o;
                for (int k = 0; k < temp.size(); k++) {
                    Object obj = temp.get(k);
                    if (obj instanceof SysOrgElement) {
                        SysOrgElement soe = (SysOrgElement) obj;
                        returnValue += soe.getFdName() + ";";
                    }
                    if (obj instanceof SysOrgPerson) {
                        SysOrgPerson soe = (SysOrgPerson) obj;
                        returnValue += soe.getFdName() + ";";
                    }
                }
            }
            
            returnValue = o == null ? "" : returnValue;
            return returnValue;
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 根据属性名获取属性
     * @param fields
     * @param fieldName
     * @return
     */
    public static Field findField(Field[] fields, String fieldName) {
        Field field = null;
        for (Field f : fields) {
            if (f.getName().equals(fieldName)) {
                field = f;
                break;
            }
        }
        return field;
    }
    
    /**
     * 过滤掉非form属性
     * @param fields
     * @return
     */
    public static Field[] filterField(Field[] fields) {
        Field[] temp = new Field[fields.length];
        int count = 0;
        for (Field field : fields) {
            if (field.getModifiers() == Modifier.PRIVATE) {
                temp[count] = field;
                count++;
            }
        }
        fields = new Field[count];
        for (int i = 0; i < count; i++) {
            fields[i] = temp[i];
        }
        return fields;
    }
    
    /**
     * 获取form属性名
     * @param fields
     * @return
     */
    public static String[] filedNames(Field[] fields) {
        if (null == fields) {
            return null;
        }
        String[] filedNames = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
            filedNames[i] = fields[i].getName();
        }
        return filedNames;
    }
    
    /**
     * 获取国际化资源中类属性名对应的值
     * @param fields
     * @param request
     * @return
     */
    public static String[] fieldResourceNames(Field[] fields, HttpServletRequest request) {
        if (null == fields) {
            return null;
        }
        String[] filedNames = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
            String value = "";
            value = ResourceUtil.getString(request, "guosenBusinessMain." + fields[i].getName(), "guosen-business");
            if (null == value || "".equals(value)) {
                value = ResourceUtil.getString(request, "guosenBusinessDetail." + fields[i].getName(), "guosen-business");
            }
            if (null == value || "".equals(value)) {
                value = ResourceUtil.getString(request, "guosenBusinessTrack." + fields[i].getName(), "guosen-business");
            }
            filedNames[i] = value;
        }
        return filedNames;
    }   
    public static void main(String[] args) {
        String[] headers = new String[]{"姓名", "性别", "出生年月", "分数"};
        List<String> data1 = new ArrayList<String>();
        data1.add("张三");
        data1.add("男");
        data1.add("1989-11-12");
        data1.add("88");
        List<String> data2 = new ArrayList<String>();
        data2.add("李四");
        data2.add("男");
        data2.add("1992-02-23");
        data2.add("75");
        List<List<String>> list = new ArrayList<List<String>>();
        list.add(data1);
        list.add(data2);
        OutputStream os = null;
        try {
            os = new FileOutputStream(new File("d:\\test.xls"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        collectExport(list, "汇总", headers, os);

    }

}


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值