因为公司需要利用poi 进行自定义的导出,乘此了解一下poi的一些常用操作

client 端

import com.alibaba.excel.metadata.BaseRowModel;
import com.hiberate.huijpa.pojo.EmpExcelModel;
import com.hiberate.huijpa.util.ReflectUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.Test;import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;/*** @author liyhu* @date 2019年09月28日*/
public class PoiModelClient {public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {String sheetName="one";List<BaseRowModel> data=new ArrayList<>();for (int i = 0; i < 9; i++) {EmpExcelModel model=new EmpExcelModel();model.setMobile("mobile"+i);model.setCardPassword("pwd"+i);model.setCardSn("sn"+i);model.setCardNo("no"+i);model.setFreezeStatus("正常");data.add(model);}Workbook wb = ExcelUtil.createExcel(sheetName, data);try (FileOutputStream os = new FileOutputStream("D:\\a.xlsx")){wb.write(os);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}System.out.println("ok");}
}

工具类

import com.alibaba.excel.annotation.ExcelProperty;import com.alibaba.excel.metadata.BaseRowModel;import com.hiberate.huijpa.util.ReflectUtil;import org.apache.commons.lang3.StringUtils;import org.apache.poi.ss.usermodel.*;import org.apache.poi.ss.util.CellRangeAddress;import org.apache.poi.ss.util.CellRangeAddressList;import org.apache.poi.xssf.usermodel.XSSFRichTextString;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.util.*;import java.util.regex.Matcher;import java.util.regex.Pattern;

/** * @author liyhu * @date 2019年09月28日 */public class ExcelUtil {

    private static short text;    private static Font blodFont ;// 粗字    private static Font redFont; // 红字    private static Workbook globalWorkBook =new XSSFWorkbook();//  匹配这种格式  *状态[正常/立即冻结/售完冻结]    private static Pattern pullDownPattern = Pattern.compile("[\\u4e00-\\u9fa5]+\\[([\\u4e00-\\u9fa5]+/[\\u4e00-\\u9fa5|/]+)]$");    static {        DataFormat dataFormat = globalWorkBook.createDataFormat();//创建格式化对象        text=dataFormat.getFormat("TEXT");

        blodFont= globalWorkBook.createFont();        blodFont.setBold(true);// 加粗        blodFont.setFontName("宋体");        blodFont.setFontHeightInPoints((short) 14);// 14号字体

        redFont = globalWorkBook.createFont();        redFont.setBold(true);        redFont.setFontName("宋体");        redFont.setColor(Font.COLOR_RED);    }

    /**     * 这里的 workbook 不能用全局的 workbook     * @param workbook     * @return     */    private static CellStyle crateTitleCellStyle(Workbook workbook){        CellStyle titleStyle = workbook.createCellStyle();        //标题样式        titleStyle.setAlignment(HorizontalAlignment.CENTER);        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        titleStyle.setBorderBottom(BorderStyle.THIN);        titleStyle.setBorderRight(BorderStyle.THIN);

        titleStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);        return titleStyle;    }

    /**     * 创建标题     * @param workbook     * @param sheet     * @param colWidthMap     */    private static void setHeader(Workbook workbook, Sheet sheet, Map<String, String> headerMap, Map<Integer, Integer> colWidthMap, int startRow){        Row titleRow = sheet.createRow(startRow);        CellStyle textStyle = workbook.createCellStyle();        //标题样式        textStyle.setDataFormat(text);

        //这里不能和类里的font公用        Font blodFont = workbook.createFont();        blodFont.setBold(true);        blodFont.setFontName("宋体");        blodFont.setFontHeightInPoints((short) 14);

        CellStyle titleStyle= crateTitleCellStyle(workbook);        titleStyle.setFont(blodFont);

        int index = 0;        for (Map.Entry<String, String> header : headerMap.entrySet()) {            Cell cell = titleRow.createCell(index);            cell.setCellStyle(titleStyle);            String excelPropertyVal = header.getValue();

            Matcher matcher = pullDownPattern.matcher(excelPropertyVal);            if(matcher.find()){// 创建该列的下拉                String[] subjects  = matcher.group(1).split("/");                DataValidationHelper helper = sheet.getDataValidationHelper();                DataValidationConstraint constraint = helper.createExplicitListConstraint(subjects);                CellRangeAddressList  addressList = new CellRangeAddressList(startRow + 1, startRow+50, index, index);                DataValidation dataValidation = helper.createValidation(constraint, addressList);                sheet.addValidationData(dataValidation);            }

            setColWidth(colWidthMap,excelPropertyVal,index,true);            RichTextString richTextString = new XSSFRichTextString(excelPropertyVal);            richTextString.applyFont(blodFont);            if (richTextString.getString().startsWith("*")) {                richTextString.applyFont(0, 1, redFont);            }            cell.setCellValue(richTextString);            sheet.setDefaultColumnStyle(index, textStyle);            index++;        }    }

    private static void setColWidth(Map<Integer, Integer> colWidthMap, String val, int index, boolean isHeader){        int length = val.length();        Integer defaultColWidth = colWidthMap.get(index);        if (length > defaultColWidth) {            if(isHeader){// 标题则是字数的两倍                length *= 2;            }            colWidthMap.put(index, length );        }    }

    /**     * 这里的 workbook 不能用全局的 workbook <br/>     * 获取数据单元格样式     * @return     * @param workbook     */    private static CellStyle createDataCellStyle(Workbook workbook){        CellStyle dataStyle = workbook.createCellStyle();        dataStyle.setAlignment(HorizontalAlignment.CENTER);        dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);        dataStyle.setDataFormat(text);        return dataStyle;    }

    /**     * 设置单元格数据     * @param sheet     * @param dataMapList     * @param headerMap     * @param colWidthMap     * @param startRow     */    private static void setData(Workbook workbook, Sheet sheet, List<Map<String, Object>> dataMapList, Map<String, String> headerMap, Map<Integer, Integer> colWidthMap, int startRow){        CellStyle dataStyle= createDataCellStyle(workbook);        int rowIndex = 0;        for (Map<String, Object> beanMap : dataMapList) {            Row row = sheet.createRow(rowIndex + startRow);            int colIndex = 0;            for (Map.Entry<String, String> entry : headerMap.entrySet()) {// 遍历标题                Cell cell = row.createCell(colIndex);                String key = entry.getKey();                Object val = beanMap.get(key);// 根据标题找到对应的值                String valString = "";                if(val != null){                    valString = beanMap.get(key).toString();                }                cell.setCellValue(valString);                cell.setCellStyle(dataStyle);

                setColWidth(colWidthMap,valString,colIndex, false);                colIndex++;            }            rowIndex++;        }    }

    public static Workbook createExcel(String sheetName, List<BaseRowModel> data,Class clazz) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {        Workbook workbook = new XSSFWorkbook();        Sheet sheet = workbook.createSheet(sheetName);        sheet.setDefaultRowHeight((short) (2 * 256));//设置默认行高        Map<String, String> headerMap = ReflectUtil.getBeanExcelProperty(clazz);        int colNum = headerMap.size();// 列的数量        int startRow = 0;

        Map<Integer, Integer> colWidthMap = new HashMap<>();        for (int i = 0; i < colNum; i++) {// 设置默认列宽            colWidthMap.put(i, 14);        }        setHeader(workbook,sheet,headerMap,colWidthMap,startRow);        if(!CollectionUtils.isEmpty(data)){            List<Map<String, Object>> dataMapList = new ArrayList<>();            for (BaseRowModel model : data) {                Map<String, Object> map = ReflectUtil.beanToMap(model);                dataMapList.add(map);            }            setData(workbook,sheet,dataMapList,headerMap,colWidthMap,startRow + 1);        }

        for (Map.Entry<Integer, Integer> entry : colWidthMap.entrySet()) {            sheet.setColumnWidth(entry.getKey(), entry.getValue() * 256);//设置每列宽度        }        return workbook;    }

    public static TreeMap<Integer,String>  getSortMap(Class<?> clazz){        TreeMap<Integer,String> treeMap=new TreeMap<>();        Field[] fields = clazz.getDeclaredFields();        for (Field field : fields) {            ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);            if(excelProperty == null){                continue;            }            treeMap.put(excelProperty.index(),field.getName());        }        return treeMap;    }

}

 实体转换工具类

 

import com.alibaba.excel.annotation.ExcelProperty;
import org.apache.commons.beanutils.PropertyUtilsBean;import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;/*** @author liyhu* @date 2019年08月27日*/
public class ReflectUtil {public static <T>T mapToProperties(Map<String,Object> map,Class<T> tClass) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException {T t = tClass.newInstance();PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(t);for (PropertyDescriptor descriptor : descriptors) {String name = descriptor.getName();if("class".equals(name)){continue;}Object val = map.get(name);if(val != null){propertyUtilsBean.setProperty(t,name,val);}}return t;}public static Map<String,Object> commonBeanToMap(Object obj) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);Map<String,Object> resultMap=new HashMap<>(descriptors.length);for (PropertyDescriptor descriptor : descriptors) {String name = descriptor.getName();if("class".equals(name)){continue;}Object val = propertyUtilsBean.getNestedProperty(obj, name);if(val != null){resultMap.put(name,val);}}return resultMap;}public static Map<String,Object> beanToMap(Object obj) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {TreeMap<Integer,String> treeMap=new TreeMap<>();Class<?> aClass = obj.getClass();PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);Map<String,Object> resultMap=new HashMap<>(descriptors.length);for (PropertyDescriptor descriptor : descriptors) {String name = descriptor.getName();if("class".equals(name)){continue;}Object val = propertyUtilsBean.getNestedProperty(obj, name);if(val != null){resultMap.put(name,val);if("cellStyleMap".equals(name)){continue;}Field field = aClass.getDeclaredField(name);ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);if(excelProperty != null){treeMap.put(excelProperty.index(),name);}}}Map<String,Object> result=new LinkedHashMap<>();for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {Object val = resultMap.get(entry.getValue());result.put(entry.getValue(),val);}return result;}}

  

转载于:https://www.cnblogs.com/dongma/p/11603637.html

利用apache 的PropertyUtilsBean 实现map和pojo相互转换相关推荐

  1. java后台处理excel_java后台利用Apache poi 生成excel文档提供前台下载示例

    之前在项目中会用到在java在后台把数据填入Word文档的模板来提供前台下载,为了自己能随时查看当时的实现方案及方便他人学习我写了这篇博客,访问量已经是我写的博客里第一了.于是乎我在学会用Java在后 ...

  2. 利用apache+wsgi运行你的django网站 - Open Idea - 博客大巴

    利用apache+wsgi运行你的django网站 - Open Idea - 博客大巴 利用apache+wsgi运行你的django网站 - Open Idea - 博客大巴 利用apache+w ...

  3. 利用Idea中Gson插件快速编辑POJO类

    利用Idea中Gson插件快速编辑POJO类 (1)需求说明 现在有一个hashmap,想写一个POJO类实现它所有字段的get.set方法,当hashmap中字段较多的时候,过程会变成很繁琐的体力活 ...

  4. java利用apache pdfbox工具裁剪PDF文件

    java利用apache pdfbox工具裁剪PDF文件 一.导入apache pdfbox工具jar包 maven仓库导入工具包 <dependency><groupId>o ...

  5. 利用Apache端口转发实现虚拟主机服务器php+jsp共用80端口

    由于某些蛋疼的事儿,服务器上面必须同时跑jsp和php,更蛋疼的是两个服务器要共用80端口!当然,郁闷的是还必须建立相对应的虚拟主机!今天,待小弟来解决此问题! 需求分析: 1,实现虚拟主机; 2,实 ...

  6. 利用Apache ab以及GNUPlot来进行Web测试

    最近写了几个测试脚本,希望要观察使用PUT方式上传文件和使用POST方式上传文件,两者效率的差别. 分别是: put_client.php          模拟客户端发送PUT请求 put_serv ...

  7. 转换实体类_利用Java反射机制进行Map和JavaBean间转换

    Java中利用反射进行Map和JavaBean间转换 在日常工作中,有时候我们可能会遇到以下这样的情况发生. 例如: (1)后端接受一个参数Map param(可能是前端form维护的一个对象...) ...

  8. java apache.poi_Java利用apache的POI操作Excel

    最近在写一些报表的活,顺便总结下...第一篇博文,希望多多指教. 项目中经常会设计到一些数据的报表问题,目前java中操作Excel的插件也有很多 ,我说下用apache的POI操作Excel的方法. ...

  9. 黑客利用Apache Struts 2漏洞在服务器上传递Cerberus勒索软件

    前一阵,我们对Apache Strust 2的CVE-2017-5638漏洞进行了预警,最近F5实验室的研究人员发现Apache Struts 2 漏洞被网络罪犯用于传递Cerber勒索软件. 实际上 ...

最新文章

  1. python如何播放视频_如何用python做一个视频搜索+播放器
  2. 如何捕获和分析 JavaScript Error
  3. VTK:相互作用之MoveAVertexUnstructuredGrid
  4. C语言学习之企业发放的奖金根据利润提成。利润I低于或等于100000元的,奖金可提成10%;
  5. 特征工程(part5)--分类型变量
  6. add_metrology_object_generic将测量对象添加到计量模型中
  7. wxpython 可视化开发pdf_MicroPython for the Internet of Things.pdf
  8. c语言科学计数法_C入门:C语言中数据的储存(上)
  9. 硬核!原型和原型链详解
  10. mysql分区表mycat_MySQL 中间件之Mycat垂直分表配置
  11. ncurses鼠标事件:mousemask(),ALL_MOUSE_EVENTS,KEY_MOUSE,getmouse(),mouse_grafo(),wmouse_trafo()
  12. redis数据类型之hash入门
  13. php mescroll,mescroll快速入门
  14. 测试用例设计设计方法——正交实验法
  15. 矩阵求导及其链式法则
  16. fpga pcie转串口驱动
  17. VS2017出现的神奇错误HRSULT:0x80041FE2
  18. windows计算机查看里设置,windows10电脑配置怎么查看
  19. windows下AV1的编译
  20. Shell 字符串转数组的三种方式

热门文章

  1. Music Game
  2. CodeForces - 946C String Transformation
  3. css之使用clearfix类清除浮动
  4. vector java 复制_Java性能优化必知的40个细节(珍藏版):Jvm调优+MySQL+Tomcat
  5. C++简单实现 前缀树
  6. HDU 6188 2017广西邀请赛:Duizi and Shunzi
  7. HDU 6166 2017 多校训练:Senior Pan(最短路)
  8. bzoj 1611: [Usaco2008 Feb]Meteor Shower流星雨(DP)
  9. bzoj 4033: [HAOI2015]树上染色(树形DP)
  10. HDU 2089:不要62(数位DP)