实现功能 --批量导出excel 文件,配置一个sheet多少条数据,根据查询数据量的多少确定生成几个sheet页。

pom 文件导入ExcelUtils工具包,依赖于poi包。

<!-- https://mvnrepository.com/artifact/org.hellojavaer/poi-excel-utils -->
<dependency>
    <groupId>org.hellojavaer</groupId>
    <artifactId>poi-excel-utils</artifactId>
    <version>1.1.0-beta</version>
</dependency>

找到ExcelUtils工具包,重构代码。

  1. package cn.enn.chaoscloud.master.utils;
  2.  
  3. import com.lkx.util.StringUtil;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.poi.hssf.usermodel.HSSFCellStyle;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.DateUtil;
    import org.springframework.beans.BeanUtils;
  4.  
  5. import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.Serializable;
    import java.lang.reflect.Method;
    import java.math.BigDecimal;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.*;
  6.  
  7. @Slf4j
    public class ExcelUtils implements Serializable {
  8.  
  9. private static final long serialVersionUID = 1L;
  10.  
  11. /**
    * getMap:(将传进来的表头和表头对应的属性存进Map集合,表头字段为key,属性为value)
    *
    * @author likaixuan
    * @param
    * : String keyValue = "手机名称:phoneName,颜色:color,售价:price";
    * @return
    * @since JDK 1.7
    */
    public static Map<String, String> getMap(String keyValue) {
    Map<String, String> map = new HashMap<String, String>();
    if (keyValue != null) {
    String[] str = keyValue.split(",");
    for (String element : str) {
    String[] str2 = element.split(":");
    map.put(str2[0], str2[1]);
    }
    }
    return map;
    }
  12.  
  13. /**
    * @author likaixuan
    * @param
    * @return List
    * @Date 2018年5月9日 21:42:24
    * @since JDK 1.7
    */
    public static List<String> getList(String keyValue) {
    List<String> list = new ArrayList<String>();
    if (keyValue != null) {
    String[] str = keyValue.split(",");
  14.  
  15. for (String element : str) {
    String[] str2 = element.split(":");
    list.add(str2[0]);
    }
    }
    return list;
    }
  16.  
  17. /**
    * setter:(反射的set方法给属性赋值)
    *
    * @author likaixuan
    * @param obj
    * 具体的类
    * @param att
    * 类的属性
    * @param value
    * 赋予属性的值
    * @param type
    * 属性是哪种类型 比如:String double boolean等类型
    * @throws Exception
    * @since JDK 1.7
    */
    public static void setter(Object obj, String att, Object value, Class<?> type, int row, int col, Object key)
    throws Exception {
    try {
    Method method = obj.getClass().getMethod("set" + StringUtil.toUpperCaseFirstOne(att), type);
    method.invoke(obj, value);
    } catch (Exception e) {
    throw new Exception("第" + (row + 1) + " 行 " + (col + 1) + "列 属性:" + key + " 赋值异常 " + e);
    }
  18.  
  19. }
  20.  
  21. /**
    * getAttrVal:(反射的get方法得到属性值)
    *
    * @author likaixuan
    * @param obj
    * 具体的类
    * @param att
    * 类的属性
    * @param
    *
    * @param type
    * 属性是哪种类型 比如:String double boolean等类型
    * @throws Exception
    * @since JDK 1.7
    */
    public static Object getAttrVal(Object obj, String att, Class<?> type) throws Exception {
    try {
    Method method = obj.getClass().getMethod("get" + StringUtil.toUpperCaseFirstOne(att));
    Object value = new Object();
    value = method.invoke(obj);
    return value;
    } catch (Exception e) {
    log.error(e.getMessage(), e);
    return null;
    }
  22.  
  23. }
  24.  
  25. /**
    * getValue:(得到Excel列的值)
    *
    * @author likaixuan
    * @param
    * @return
    * @throws Exception
    * @since JDK 1.7
    */
    public static void getValue(Cell cell, Object obj, String attr, Class attrType, int row, int col, Object key)
    throws Exception {
    Object val = null;
    if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
    val = cell.getBooleanCellValue();
  26.  
  27. } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
    if (DateUtil.isCellDateFormatted(cell)) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
    if (attrType == String.class) {
    val = sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue()));
    } else {
    val = dateConvertFormat(sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue())));
    }
    } catch (ParseException e) {
    throw new Exception("第" + (row + 1) + " 行 " + (col + 1) + "列 属性:" + key + " 日期格式转换错误 ");
    }
    } else {
    if (attrType == String.class) {
    cell.setCellType(Cell.CELL_TYPE_STRING);
    val = cell.getStringCellValue();
    } else if (attrType == BigDecimal.class) {
    val = new BigDecimal(cell.getNumericCellValue());
    } else if (attrType == long.class) {
    val = (long) cell.getNumericCellValue();
    } else if (attrType == Double.class) {
    val = cell.getNumericCellValue();
    } else if (attrType == Float.class) {
    val = (float) cell.getNumericCellValue();
    } else if (attrType == int.class || attrType == Integer.class) {
    val = (int) cell.getNumericCellValue();
    } else if (attrType == Short.class) {
    val = (short) cell.getNumericCellValue();
    } else {
    val = cell.getNumericCellValue();
    }
    }
  28.  
  29. } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
    val = cell.getStringCellValue();
    }
  30.  
  31. setter(obj, attr, val, attrType, row, col, key);
    }
  32.  
  33. /**
    * exportExcel:(导出Excel)
    *
    * @author likaixuan
    * @param
    * @return
    * @throws Exception
    * @since JDK 1.7
    */
    public static void exportExcel(HSSFWorkbook wb,OutputStream outputStream, String keyValue, List<?> list, String classPath,int sheetNum,int pageNum)
    throws Exception {
  34.  
  35. Map<String, String> map = getMap(keyValue);
    List<String> keyList = getList(keyValue);
  36.  
  37. Class<?> demo = null;
    demo = Class.forName(classPath);
    Object obj = demo.newInstance();
  38.  
  39. // 建立新的sheet对象(excel的表单)
    String sheetName = "sheet"+String.valueOf(sheetNum);
    HSSFSheet sheet = wb.createSheet(sheetName);
    // 声明样式
    HSSFCellStyle style = wb.createCellStyle();
    // 居中显示
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    // 在sheet里创建第一行为表头,参数为行索引(excel的行),可以是0~65535之间的任何一个
    HSSFRow rowHeader = sheet.createRow(0);
    // 创建单元格并设置单元格内容
  40.  
  41. // 存储属性信息
    Map<String, String> attMap = new HashMap();
    int index = 0;
  42.  
  43. for (String key : keyList) {
    rowHeader.createCell(index).setCellValue(key);
    attMap.put(Integer.toString(index), map.get(key).toString());
    index++;
    }
  44.  
  45. // 在sheet里创建表头下的数据
    for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
    HSSFRow row = sheet.createRow(i + 1);
    for (int j = 0; j < map.size(); j++) {
  46.  
  47. Class<?> attrType = BeanUtils.findPropertyType(attMap.get(Integer.toString(j)),
    new Class[] { obj.getClass() });
  48.  
  49. Object value = getAttrVal(list.get(i), attMap.get(Integer.toString(j)), attrType);
    if (null == value) {
    value = "";
    }
    row.createCell(j).setCellValue(value.toString());
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    }
    }
    // 输出Excel文件
    try {
    if(sheetNum == pageNum || pageNum == 0){
    wb.write(outputStream);
    outputStream.close();
    }
    } catch (FileNotFoundException e) {
    throw new FileNotFoundException("导出失败!" + e);
    } catch (IOException e) {
    throw new IOException("导出失败!" + e);
    }
  50.  
  51. }
  52.  
  53. /**
    * String类型日期转为Date类型
    *
    * @param dateStr
    * @return
    * @throws ParseException
    * @throws Exception
    */
    public static Date dateConvertFormat(String dateStr) throws ParseException {
    Date date = new Date();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    date = format.parse(dateStr);
    return date;
    }
    }
  54.  
  55. 调用封装工具类
  1. public static final int page_size = 10000;
  1. @PostMapping("queryUnusedGasListExcel")
    public byte[] queryUnusedGasListExcel(@RequestBody UnusedGasDTO unusedGasDTO) throws Exception{
    byte[] bytes = null;
    try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){
    int list_count = unusedGasService.findCountList(unusedGasDTO);
    // 根据行数求数据提取次数
    int export_times = list_count % page_size > 0 ? list_count / page_size
    + 1 : list_count / page_size;
  2.  
  3. // 创建HSSFWorkbook对象(excel的文档对象)
    HSSFWorkbook wb = new HSSFWorkbook();
    for (int j = 0; j < export_times; j++) {
    unusedGasDTO.setPositionNum(j*page_size);
    unusedGasDTO.setShowNum(page_size);
    List<UnusedGasVO> list = unusedGasService.downLoadByList(unusedGasDTO);
    int len = list.size() < page_size ? list.size() : page_size;
    String keyValue = "客户名称:customerName,房产名称:houseName,表钢号:meterCode,余额(元):balance,表底数:meterBase,未用气天数:unusedGasDays,客户类型编码:customerCode,联系方式:customerTel,表型名称:metersTypeName,合约号:contractNum," +
    "集团id:groupId,集团编码:groupName,公司id:companyId,公司编码:companyCode,公司名称:companyName," +
    "客户电话:customerTel,房产编码:houseCode,表型编码:meterType,未用气天数时间:unusedGasTime";
    //HSSFWorkbook ;j+1 sheet当前页; export_times sheet总页数
    /**
    * HSSFWorkbook
    * outputStream流
    * 根据反射获取实体类,并且赋值
    * list 查询到的实体集合
    * classPath list 中实体的路径,反射用到
    * j+1 要写入sheet的页数
    * 重新查询数据的次数
    */
    ExcelUtils.exportExcel(wb,byteArrayOutputStream, keyValue, list, "cn.enn.chaoscloud.domain.archives.meter.vo.UnusedGasVO", j+1,export_times);
    }
    bytes = byteArrayOutputStream.toByteArray();
  4.  
  5. }catch (Exception e){
    log.error(e.getMessage(), e);
    }
    return bytes;
    }

工具类--Excel 导出poi的更多相关文章

  1. C#常用工具类——Excel操作类

    /// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...

  2. C#常用工具类——Excel操作类(ZT)

    本文转载于: http://www.cnblogs.com/zfanlong1314/p/3916047.html /// 常用工具类——Excel操作类 /// <para> ----- ...

  3. .NET开发工具之Excel导出公共类

    来源:Pino晨 链接:cnblogs.com/chenxygx/p/5954870.html 说明 最近接了一个任务,就是做一个列表的Excel导出功能.并且有很多页面都会使用这个功能. 导出的Ex ...

  4. 使用hutool工具类进行导出

    引入依赖为: <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</ ...

  5. java工具类-excel jxl

    jxl-2.6.9.14.jarimport net.sf.jxls.transformer.XLSTransformer;//jxls-core-1.0.2.jarimport java.io.Fi ...

  6. Java基础学习总结(49)——Excel导入导出工具类

    在项目的pom文件中引入 <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifac ...

  7. Excel和Word 简易工具类,JEasyPoi 2.1.5 版本发布

    Excel和Word 简易工具类,JEasyPoi 2.1.5 版本发布 摘要: jeasypoi 功能如同名字easy,主打的功能就是容易,让一个没见接触过poi的人员 就可以方便的写出Excel导 ...

  8. Excel解析easyexcel工具类

    Excel解析easyexcel工具类 easyexcel解决POI解析Excel出现OOM <!-- https://mvnrepository.com/artifact/com.alibab ...

  9. Java导出防止小数显示不全工具类

    1.说明 在做项目的过程中,发现导出功能中的数据显示不全,如"0.4",会显示成".4":"-0.8"会显示成"-.8" ...

随机推荐

  1. Xcode 5 下的单元测试

    新版Xcode 5和Server发布以后,apple对单元测试的支持是越来越好了.从这一点看出apple对单元测试的也是越来越重视了. 这篇Blog就简单的介绍这集成化测试功能. Server更新后是 ...

  2. javaweb登录验证码的实现

    第一种 第一步:  JSP <li><input name="validCode"  id="validCode" type="te ...

  3. jquery 找到指定父级指定子集

    其中 closest() : jquery 1.3 新增 从元素本身开始,逐级向上级元素匹配,并返回最先匹配的元素. 其中 find() : 搜索所有与指定表达式匹配的元素.这个函数是找出正在处理的元 ...

  4. select change()

    $(".learnStageId").change(function(){ var id = $(this).val(); $(".gradeId").find ...

  5. processing模拟三角级数合成方波过程

    代码 1: int radius = 2; 2: int[] accumys; 3: int times = 0; 4: 5: float scale = 1; 6: int origin = 400 ...

  6. css3水平垂直居中(不知道宽高同样适用)

    css水平垂直居中 第一种方法: 在父div里加: display: table-cell; vertical-align: middle; text-align: center; 内部div设置: ...

  7. Java内部类类型

    可以在类中的任何位置定义内部类,并在其中编写Java语句.有三种类型的内部类. 内部类的类型取决于位置和声明的方式. 成员内部类 局部内部类 匿名内部类 成员内部类 成员内部类在类中声明的方式与声明成 ...

  8. 关于软件IntelliJ IDEA的使用技巧(三)

    二,IntelliJ IDEA的工具栏介绍 2,IntelliJ IDEA菜单栏 (9)Tools工具 ✌1.Tasks & Contexts: ✌2.Generate JavaDoc: ✌3 ...

  9. 怎么在vue-cli中利用 :class去做一个底层背景或者文字的点击切换

    // html <div class="pusherLists" :class="{hidden: isHidden}"> <span @cl ...

  10. TurtleBOT3

    ubuntu更换源 sudo cp /etc/apt/sources.list /etc/apt/sources_backup.list sudo gedit /etc/apt/sources.lis ...