POI导出导入

本文介绍了使用Java POI库进行Excel文件的导出和导入操作,通过示例代码展示了具体实现步骤。
摘要由CSDN通过智能技术生成

POI导出导入源码

  /**
   * 根据字段名获取字段对象
   *
   * @param fieldName 字段名
   * @param clazz     包含该字段的类
   * @return 字段
   */
  public static Field getFieldByName(String fieldName, Class<?> clazz) {
   
    // 拿到本类的所有字段
    Field[] selfFields = clazz.getDeclaredFields();

    // 如果本类中存在该字段,则返回
    for (Field field : selfFields) {
   
      //如果本类中存在该字段,则返回
      if (field.getName().equals(fieldName)) {
   
        return field;
      }
    }

    // 否则,查看父类中是否存在此字段,如果有则返回
    Class<?> superClazz = clazz.getSuperclass();
    if (superClazz != null && superClazz != Object.class) {
   
      //递归
      return getFieldByName(fieldName, superClazz);
    }

    // 如果本类和父类都没有,则返回空
    return null;
  }

  /**
   * 根据字段名获取字段值
   *
   * @param fieldName 字段名
   * @param o         对象
   * @return 字段值
   * @throws Exception 异常
   */
  public static Object getFieldValueByName(String fieldName, Object o)
    throws Exception {
   

    Object value = null;
    //根据字段名得到字段对象
    Field field = getFieldByName(fieldName, o.getClass());

    //如果该字段存在,则取出该字段的值
    if (field != null) {
   
      field.setAccessible(true);//类中的成员变量为private,在类外边使用属性值,故必须进行此操作
      value = field.get(o);//获取当前对象中当前Field的value
    } else {
   
      throw new Exception(o.getClass().getSimpleName() + "类不存在字段名 "
        + fieldName);
    }

    return value;
  }

  /**
   * 根据带路径或不带路径的属性名获取属性值,即接受简单属性名,
   * 如userName等,又接受带路径的属性名,如student.department.name等
   *
   * @param fieldNameSequence 带路径的属性名或简单属性名
   * @param o                 对象
   * @return 属性值
   * @throws Exception 异常
   */
  public static Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception {
   
    Object value = null;

    // 将fieldNameSequence进行拆分
    String[] attributes = fieldNameSequence.split("\\.");
    if (attributes.length == 1) {
   
      value = getFieldValueByName(fieldNameSequence, o);
    } else {
   
      // 根据数组中第一个连接属性名获取连接属性对象,如student.department.name
      Object fieldObj = getFieldValueByName(attributes[0], o);
      //截取除第一个属性名之后的路径
      String subFieldNameSequence = fieldNameSequence
        .substring(fieldNameSequence.indexOf(".") + 1);
      //递归得到最终的属性对象的值
      value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj);
    }
    return value;

  }

  public static String getCellFormatValue(HSSFCell cell) {
   
    String cellValue = "";
    DecimalFormat df = new DecimalFormat("#.0000");
    if (cell != null) {
   
      switch (cell.getCellType()) {
   
        case STRING:
          cellValue = cell.getRichStringCellValue().getString().trim();
          break;
        case NUMERIC:
          cellValue = doubleTrans(cell.getNumericCellValue());
          if (HSSFDateUtil.isCellDateFormatted(cell)) {
   
            Date d = cell.getDateCellValue();
            DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
            cellValue = formater.format(d).toString();
          }
          break;
        case BOOLEAN:
          cellValue = String.valueOf(cell.getBooleanCellValue()).trim();
          break;
        case FORMULA:
          cellValue = cell.getCellFormula();
          break;
        default:
          cellValue = "";
      }
    }
    return cellValue;
  }

demo实现


 @Override
  public void export(List<ProductCodeBaseCategory> productCodeBaseCategoryList)  {
   
    HttpServletResponse response = ServletUtils.getResponse();
    String excelName = "产品代码" + System.currentTimeMillis();

    response.reset();
    response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件

    try {
   
      response.setHeader("Content-disposition", "attachment; filename="
        + new String(excelName.getBytes("gb2312"), "ISO-8859-1") + ".xls");
      HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
      HSSFSheet sheet = hssfWorkbook.createSheet(excelName);
      HSSFCellStyle cellStyle = hssfWorkbook.createCellStyle();
      cellStyle.setAlignment(HorizontalAlignment.CENTER);
      fillSheet(productCodeBaseCategoryList, sheet, cellStyle);
      ServletOutputStream outputStream = response.getOutputStream();
      hssfWorkbook.write(outputStream);
      outputStream.flush();
      outputStream.close();
    } catch (Exception e) {
   
      e.printStackTrace();
      log.error("导出Excel失败!");
      log.error(e.getMessage());
    }
  }

  private void fillSheet(List<ProductCodeBaseCategory> productCodeBaseCategoryList, HSSFSheet sheet, HSSFCellStyle cellStyle) throws Exception {
   
    //region 表头数据
    List<String> titles = new ArrayList<>();
    titles.add("产品代码");
    titles.add("同行M代码");
    titles.add("同行Y代码");
    titles.add("产品名称");
    titles.add("类别");
    titles.add("类别代码");
    titles.add("单位");
    titles.add("类型");
    titles.add("二级类别");
    titles.add("一级类别");
    titles.add("产品组别");
    titles.add("产品负责人");
    titles.add("物料属性");
    titles
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值