Java导出数据为Excel文件

Java导出数据为Excel文件

代码如下:

/**
 * 导出Excel
 * @param <T>
 */
public class ExportExcelUtil<T> {

    public final static Pattern pattern = Pattern.compile("^//d+(//.//d+)?$");

    /**
     * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
     * 此版本生成2007以上版本的文件 (文件后缀:xlsx)
     *
     * @param fileName   表格标题名
     * @param headers 表格头部标题集合
     * @param dataset 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
     *                JavaBean属性的数据类型有基本数据类型及String,Date
     */
   public void exportExcel(HttpServletResponse response, String fileName, String[] headers, Collection<T> dataset) throws Exception {

        // 可以不加,但是保证response缓冲区没有任何数据,开发时建议加上
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setBufferSize(1024);
        // 下面三行是关键代码,处理乱码问题
        // 设置响应的编码
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/x-download");
        // 设置浏览器响应头对应的Content-disposition
        response.setHeader("Content-disposition", "attachment;filename="+ new String(fileName.getBytes("UTF-8"), "iso-8859-1") + ".xlsx");

        // 声明一个工作薄
        // 内存中只创建100个对象,写临时文件,当超过100条,就将内存中不用的对象释放
        SXSSFWorkbook workbook = new SXSSFWorkbook(100);

     // 生成一个表格
        Sheet sheet = workbook.createSheet(fileName); // 工作表对象
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth(20);
        // 生成一个样式
        XSSFCellStyle cellStyle = (XSSFCellStyle)workbook.createCellStyle();
        // 设置这些样式
        cellStyle.setFillForegroundColor(new XSSFColor(java.awt.Color.gray));
        cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
        cellStyle.setBorderRight(CellStyle.BORDER_THIN);
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);
        cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
        // 生成一个字体
        XSSFFont font = (XSSFFont)workbook.createFont();
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        font.setFontName("宋体");
        font.setColor(new XSSFColor(java.awt.Color.BLACK));
        font.setFontHeightInPoints((short) 11);
        // 把字体应用到当前的样式
        cellStyle.setFont(font);
        // 生成并设置另一个样式
        XSSFCellStyle style2 = (XSSFCellStyle)workbook.createCellStyle();
        style2.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE));
        style2.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        style2.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(XSSFCellStyle.BORDER_THIN);
        style2.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        // 生成另一个字体
        XSSFFont font2 = (XSSFFont)workbook.createFont();
        font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);

        // 产生表格标题行
        Row row = sheet.createRow(0); // 行对象
        Cell cellHeader; // 列对象
        for (int i = 0; i < headers.length; i++) {
            cellHeader = row.createCell(i);
            cellHeader.setCellStyle(cellStyle);
            cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
        }
     if (null != dataset && dataset.size() != 0 && !dataset.isEmpty()) {
          // 遍历集合数据,产生数据行
          Iterator<T> it = dataset.iterator();
          int index = 0;
          T t;
          Field[] fields;
          Field field;
          XSSFRichTextString richString;
          // p
          Matcher matcher;
          String fieldName;
          String getMethodName;
          Cell cell;
          Class tCls;
          Method getMethod;
          Object value;
          String textValue;
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
          while (it.hasNext()) {
              index++;
              row = sheet.createRow(index);
              t = (T) it.next();
              // 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
              fields = t.getClass().getDeclaredFields();
              for (int i = 0; i < fields.length; i++) {
                  cell = row.createCell(i);
                  cell.setCellStyle(style2);
                  field = fields[i];
                  fieldName = field.getName();
                  getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
                          + fieldName.substring(1);
                  try {
                      tCls = t.getClass();
                      getMethod = tCls.getMethod(getMethodName, new Class[]{});
                      value = getMethod.invoke(t, new Object[]{});
                      // 判断值的类型后进行强制类型转换
                      textValue = null;
                      if (value instanceof Integer) {
                          cell.setCellValue((Integer) value);
                      } else if (value instanceof Float) {
                          textValue = String.valueOf((Float) value);
                          cell.setCellValue(textValue);
                      } else if (value instanceof Double) {
                          textValue = String.valueOf((Double) value);
                          cell.setCellValue(textValue);
                      } else if (value instanceof Long) {
                          cell.setCellValue((Long) value);
                      }
                      if (value instanceof Boolean) {
                          textValue = "是";
                          if (!(Boolean) value) {
                              textValue = "否";
                          }
                      } else if (value instanceof Date) {
                          textValue = sdf.format((Date) value);
                      } else {
                          // 其它数据类型都当作字符串简单处理
                          if (value != null) {
                              textValue = value.toString();
                          }
                      }
                      if (textValue != null) {
                          matcher = pattern.matcher(textValue);
                          if (matcher.matches()) {
                              // 是数字当作double处理
                              cell.setCellValue(Double.parseDouble(textValue));
                          } else {
                              richString = new XSSFRichTextString(textValue);
                              cell.setCellValue(richString);
                          }
                      }
                } catch (SecurityException e) {
                      e.printStackTrace();
                  } catch (NoSuchMethodException e) {
                      e.printStackTrace();
                  } catch (IllegalArgumentException e) {
                      e.printStackTrace();
                  } catch (IllegalAccessException e) {
                      e.printStackTrace();
                  } catch (InvocationTargetException e) {
                      e.printStackTrace();
                  } finally {
                      // 清理资源
                  }
               }
           }
      }
         OutputStream outputStream = response.getOutputStream(); // 打开流
        try {
            workbook.write(outputStream); // 写入流
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            outputStream.flush(); // 刷新流
            outputStream.close(); // 关闭流
        }
    }
}

maven配置如下:

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>3.9</version>
</dependency>

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>3.9</version>
</dependency>

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml-schemas</artifactId>
  <version>3.9</version>
</dependency>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java-version

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值