POI导出Excel表格(可选时间,文本,数字等)到浏览器指定路径

导出选择内容的格式 

 ExcelHeader.java

public class ExcelHeader {

  //表头名称
  private String title;

  //对应表数据的code名称
  private String name;

  //数据类型
  private String dateType;

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getDateType() {
    return dateType;
  }

  public void setDateType(String dateType) {
    this.dateType = dateType;
  }

  public ExcelHeader() {
  }

  public ExcelHeader(String title, String name, String dateType) {
    this.title = title;
    this.name = name;
    this.dateType = dateType;
  }

  @Override
  public String toString() {
    return "TableHeader{" +
        "title='" + title + '\'' +
        ", name='" + name + '\'' +
        ", dateType='" + dateType + '\'' +
        '}';
  }
}

ExcelPortUtill.java 

public class ExcelPortUtill {
    private static BaseBean log = new BaseBean();
    private static final String dateTime = "yyyy-MM-dd";
    private static final String dateSecond = "yyyy-MM-dd HH:mm:ss";
    private static final String Error_EXCELPORTUTIL = "ExcelPortUtil.exportExcel";

    public static void exportExcel(HttpServletResponse response, List<ExcelHeader> listHead, List<Object> list) {
        HSSFWorkbook workbook = null;
        OutputStream output = null;
        try {
            SimpleDateFormat formatDatetime = new SimpleDateFormat(dateSecond);
            SimpleDateFormat formatDate = new SimpleDateFormat(dateTime);
            // 创建一个Excel文件
            //XSSFWorkbook workbook = new XSSFWorkbook();

            workbook = new HSSFWorkbook();
            // 创建一个工作表
            HSSFSheet sheet = workbook.createSheet("Sheet");
            // 添加表头行
            HSSFRow hssfRow = sheet.createRow(0);
            // 设置单元格格式居中
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

            // 添加表头内容
            HSSFCell headCell = null;
            for (int i = 0; i < listHead.size(); i++) {
                headCell = hssfRow.createCell(i);
                headCell.setCellValue(listHead.get(i).getTitle());
                headCell.setCellStyle(cellStyle);
            }
            //无数据写出表头
            if (list.size() != 0) {
                // workbook.write(response.getOutputStream());

                Map<String, Integer> map = new HashMap<String, Integer>();
                String k = null;

                for (int i = 0; i < listHead.size(); i++) {
                    //反射获取对象所有成员变量
                    Field[] fields = list.get(0).getClass().getDeclaredFields();
                    //表头大于单个数据长度,结束
                    if (i + 1 > fields.length) {
                        break;
                    }

                    for (int j = 0; j < list.size(); j++) {
                        k = (j + 1) + "";
                        //
                        if (map.get(k) == null) {
                            //创建第n行
                            hssfRow = sheet.createRow((int) j + 1);
                        } else {
                            //当前行已经创建的,直接拿到该行的对象
                            hssfRow = sheet.getRow(map.get(k));
                        }


                        map.put(k, (j + 1));

                        //获得对象对应的成员变量的域
                        Field field = list.get(j).getClass().getDeclaredField(listHead.get(i).getName());
                        //获的成员变量的值
                        String name = field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
                        //获得get方法
                        Method m = list.get(j).getClass().getMethod("get" + name);
                        //()m.invoke(list.get(j));

                        if ("txt".equals(listHead.get(i).getDateType())) {
                            String value = (String) m.invoke(list.get(j));
                            //获得当前行的第i个单元格
                            HSSFCell cell = hssfRow.createCell(i);
                            //封装值
                            cell.setCellValue(value);
                            //封装样式
                            cell.setCellStyle(cellStyle);
                        }
                        if ("datetime".equals(listHead.get(i).getDateType())) {
                            String date = (String) m.invoke(list.get(j));
                            Date datetime = formatDatetime.parse(date);
                            HSSFCell cell = hssfRow.createCell(i);
                            short df = workbook.createDataFormat().getFormat(dateSecond);
                            CellStyle style = workbook.createCellStyle();
                            style.setDataFormat(df);
                            cell.setCellValue(datetime);
                            cell.setCellStyle(style);
                        }
                        if ("date".equals(listHead.get(i).getDateType())) {
                            String dateStr = (String) m.invoke(list.get(j));
                            Date date = formatDate.parse(dateStr);
                            HSSFCell cell = hssfRow.createCell(i);
                            short df = workbook.createDataFormat().getFormat(dateTime);
                            CellStyle style = workbook.createCellStyle();
                            style.setDataFormat(df);
                            cell.setCellValue(date);
                            cell.setCellStyle(style);
                        }
                        if ("num".equals(listHead.get(i).getDateType())) {
                            String numStr = (String) m.invoke(list.get(j));
                            if (numStr.indexOf(".") == -1) {
                                Integer num = Integer.parseInt(numStr);
                                HSSFCell cell = hssfRow.createCell(i);
                                cell.setCellValue(num);
                                cell.setCellStyle(cellStyle);
                            } else {
                                Double.parseDouble(numStr);
                                BigDecimal cash = new BigDecimal(Double.parseDouble(numStr));
                                //小数点精确4位
                                double d2 = cash.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                                HSSFCell cell = hssfRow.createCell(i);
                                cell.setCellValue(d2);
                                cell.setCellStyle(cellStyle);
                            }
                        }
                    }
                }
            }
            String dateTime = formatDatetime.format(new Date());
            //输出流
            output = response.getOutputStream();
            //文件名称定义
            String fileName = dateTime.replace("-", "").replace("_", "") + "-" + UUID.randomUUID().toString().replace("-", "") + ".xlsx";
            //清空缓冲区
            response.reset();
            //设置文本格式类型
            response.setContentType("application/msexcel;charset=utf-8");
            //设置头
            response.setHeader("Content-disposition", "attachment;filename= " + fileName);
            //写入返回流
            workbook.write(output);

        } catch (Exception e) {
            log.writeLog(Error_EXCELPORTUTIL, e);

        } finally {
            try {
                workbook.close();
                output.close();
            } catch (Exception e) {
                log.writeLog(Error_EXCELPORTUTIL, e);
            }

        }

    }
}

TUser.java 

class TUser{
  private String id;
  private String name;
  private String date;
 
  public String getId() {
    return id;
  }
 
  public void setId(String id) {
    this.id = id;
  }
 
  public String getName() {
    return name;
  }
 
  public void setName(String name) {
    this.name = name;
  }
 
  public String getDate() {
    return date;
  }
 
  public void setDate(String date) {
    this.date = date;
  }
 
  public TUser() {
  }
 
  public TUser(String id, String name, String date) {
    this.id = id;
    this.name = name;
    this.date = date;
  }
 
  @Override
  public String toString() {
    return "TUser{" +
            "id='" + id + '\'' +
            ", name='" + name + '\'' +
            ", date='" + date + '\'' +
            '}';
  }

页面导出到浏览器指定下载路径 

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        res.setHeader("Content-type", "text/html;charset=UTF-8");
        res.setContentType("text/html;charset=UTF-8");
        ExcelHeader excelHeader1=new ExcelHeader("表头1","id","num");
        ExcelHeader excelHeader2=new ExcelHeader("表头2","name","txt");
        ExcelHeader excelHeader3=new ExcelHeader("表头3","date","date");
        ExcelHeader excelHeader4=new ExcelHeader("表头4","date","date");
        List<ExcelHeader> listHead=new ArrayList<>();
        listHead.add(excelHeader1);
        listHead.add(excelHeader2);
        listHead.add(excelHeader3);
        listHead.add(excelHeader4);
        List<Object> list=new ArrayList<>();
        TUser user=new TUser();
        user.setId("2");
        user.setName("马");
        user.setDate("2018-09-05 02:05:26");
        TUser user2=new TUser();
        user2.setId("3.456789");
        user2.setName("下雨");
        user2.setDate("2018-09-05 02:05:26");
        TUser user3=new TUser("4.56",null,"2018-09-05 02:05:26");
        TUser user4=new TUser("6.56","kkk","2018-09-05 02:05:26");
        TUser user5=new TUser("55","55","2018-09-05 02:05:26");
        list.add(user);
        list.add(user2);
        list.add(user3);
        list.add(user4);
        list.add(user5);
       
        ExcelPortUtill.exportExcel(res,listHead,list);
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值