Java导出Excel格式数据 Java使用poi组件导出Excel格式数据

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java导出Excel格式数据 Java使用poi组件导出Excel格式数据

Miss小恢灰丶   2021-04-21 我要评论

在做管理系统的时候,我想Excel的导出是我们很难规避掉的,而且这也是个很实用很人性化的功能。

Java中对于Excel的支持有很多种,比如说JXL,POI等。我这边使用的是POI进行一个Excel的操作,下面我会简单分享下POI组件的使用,以及我使用比较多一个工具类。

POI组件

poi组件是由Apache提供的组件包,主要职责是为我们的Java程序提供对于office文档的相关操作。本文主要是它对于Excel操作的一个介绍。

官方主页:http://poi.apache.org/index.html

API文档:http://poi.apache.org/apidocs/index.html

POI组件基本介绍

使用的时候我们可以发现poi组件为我们提供的操作Excel的相关类都是HSSF开头的,这些类主要是在org.apache.poi.hssf.usermodel这个包下面。里面包涵有像Excel的对象,单元格的样式,字体样式以及部分的工具类。一下介绍几个我们常用的类:

  1. HSSFWorkbook:Excel对象,相当于一个 .xls/.xlsx 文件
  2. HSSFSheet:工作表对象,Excel文件包涵的sheet,一个对象代表一个表单
  3. HSSFRow:表示表格中的行对象。
  4. HSSFCell:表示表格中的单元格对象。
  5. HSSFHeader:Excel文档Sheet的页眉。
  6. HSSFFooter:Excel文档Sheet的页脚。
  7. HSSFDataFormat:日期格式。
  8. HSSFFont:字体对象。
  9. HSSFCellStyle:单元格样式(对齐样式、边框等)
  10. HSSFComment:批注(注释)。
  11. HSSFPatriarch:和HSSFComment用于创建注释的位置。
  12. HSSFColor:颜色对象。
  13. HSSFDateUtil:日期辅助工具
  14. HSSFPrintSetup:打印辅助工具
  15. HSSFErrorConstants:错误信息表

POI组件基本操作

1.HSSFWorkbook创建‘Excel文件对象'

//创建Excel对象
HSSFWorkbook workbook = new HSSFWorkbook();

2.使用workbook 对象创建工作表对象

//创建工作表单
HSSFSheet sheet = workbook.createSheet("对象报表"); 

3.创建行和操作单元格对象

//创建HSSFRow对象 (行)
HSSFRow row = sheet.createRow(0); 

//创建HSSFCell对象 (单元格)
HSSFCell cell=row.createCell(0); 

//设置单元格的值 
cell.setCellValue("单元格中的中文"); 

4.保存Excel文件

//输出Excel文件 
FileOutputStream output=new FileOutputStream("d:\\workbook.xls"); 

workbook.write(output); 

output.flush(); 

个性化导出—样式设置

这边我列举出部分常用的样式设置的方法!

1.合并单元格,设置宽、高

// 实例化样式对象
HSSFCellStyle cellStyle = workbook.createCellStyle(); 
// 两端对齐
cellStyle.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY); 
// 垂直居中
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
// 填充图案---填充方式
cellStyle.setFillPattern(HSSFCellStyle.DIAMONDS); 
// 设置前景色 (这个要写在背景色的前面)
cellStyle.setFillForegroundColor(HSSFColor.RED.index); 
// 设置背景颜色 
cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index); 
// 设置边框
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_SLANTED_DASH_DOT); 
// 边框颜色
cellStyle.setBottomBorderColor(HSSFColor.DARK_RED.index); 
// 日期展示格式 
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));  

//将样式应用于单元格
cell.setCellStyle(cellStyle); 
//将样式应用到行 
row.setRowStyle(cellStyle);

2.设置单元格样式

// 实例化样式对象
HSSFCellStyle cellStyle = workbook.createCellStyle(); 
// 两端对齐
cellStyle.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY); 
// 垂直居中
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
// 填充图案---填充方式
cellStyle.setFillPattern(HSSFCellStyle.DIAMONDS); 
// 设置前景色 (这个要写在背景色的前面)
cellStyle.setFillForegroundColor(HSSFColor.RED.index); 
// 设置背景颜色 
cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index); 
// 设置边框
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_SLANTED_DASH_DOT); 
// 边框颜色
cellStyle.setBottomBorderColor(HSSFColor.DARK_RED.index); 
// 日期展示格式 
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));  

//将样式应用于单元格
cell.setCellStyle(cellStyle); 
//将样式应用到行 
row.setRowStyle(cellStyle);

3.设置字体

// 实例化字体对象
HSSFFont fontStyle = workbook.createFont(); 
// 字体
fontStyle.setFontName("宋体");  
// 高度 
fontStyle.setFontHeightInPoints((short)12);  
// 字体 
font.setColor(HSSFColor.BLUE.index); 
// 加粗 
fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 
// 斜体  
font.setItalic(true); 
// 下划线 
font.setUnderline(HSSFFont.U_SINGLE); 
// 将字体应用于单元格样式中
cellStyle.setFont(font);

个人应用

下面给大家分享下个人的整体使用过程!

处理的action

    //用于导出的数据集合
    List<PBillBean> dataset = new ArrayList<PBillBean>();
    //填充dataset
    for (int i = 0; i < 10; i++) {
      PBillBean bean = new PBillBean();
      dataset.add(bean);
    }
    //临时文件
    File tempFile = null;
    try {
      //Excel导出工具类
      ExportExcel<PBillBean> ex = new ExportExcel<PBillBean>();
      //导出的标题列
      String[] headers = { "标题1", "标题2", "标题3", "标题4",  "标题5", "标题6" };
      //时间格式化
      SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
      //要保存的文件名
      String filename = "bill_" + format.format(new Date()) + ".xls";
      //要保存的根目录
      String rootDir = request.getSession().getServletContext().getRealPath("/");
      //要保存的目录路径
      String path = rootDir + File.separator + "tempfile";
      File saveDir = new File(path);
      if (!saveDir.exists()) {
        saveDir.mkdirs();// 如果文件不存在则创建文件夹
      }
      //文件路径
      path = path + File.separator + filename;
      tempFile = new File(path);  //初始化临时文件
      //输出流
      OutputStream out = new FileOutputStream(tempFile);
      //实例化Excel表格
      HSSFWorkbook workbook = new HSSFWorkbook();
      //创建工作表单
      String[] sheetNames = { "对账报表" };
      for (int i = 0; i < sheetNames.length; i++) {
        workbook.createSheet(sheetNames[i]);
      }
      //导出到Excel
      ex.exportExcel(sheetNames[0], headers, dataset, out,
          "yyyy-MM-dd HH:mm", workbook);
      try {
        //保存文件
        workbook.write(out);
      } catch (IOException e) {
        e.printStackTrace();
      }
      out.close();
      // 以流的形式下载文件。
      BufferedInputStream fis = new BufferedInputStream(
          new FileInputStream(path));
      byte[] buffer = new byte[fis.available()];
      fis.read(buffer);
      fis.close();
      // 清空response
      response.reset();
      // 设置response的Header
      response.addHeader("Content-Disposition", "attachment;filename="
          + new String(filename.getBytes()));
      response.addHeader("Content-Length", "" + tempFile.length());
      OutputStream toClient = new BufferedOutputStream(
          response.getOutputStream());
      response.setContentType("application/vnd.ms-excel;charset=utf-8");
      toClient.write(buffer);
      toClient.flush();
      toClient.close();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (tempFile != null && tempFile.exists()) {
        tempFile.delete();// 删除临时文件
      }
    }

导出Excel工具类

public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern,HSSFWorkbook workbook) 
  { 
    // 声明一个工作薄  生成一个表格 
    HSSFSheet sheet = workbook.getSheet(title);
    // 设置表格默认列宽度为15个字节 
    sheet.setDefaultColumnWidth((short) 15); 
    // 生成一个样式 
    HSSFCellStyle style = workbook.createCellStyle(); 
    // 设置这些样式 
    style.setFillForegroundColor(HSSFColor.SKY_BLUE.index); 
    style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN); 
    style.setBorderLeft(HSSFCellStyle.BORDER_THIN); 
    style.setBorderRight(HSSFCellStyle.BORDER_THIN); 
    style.setBorderTop(HSSFCellStyle.BORDER_THIN); 
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
    // 生成一个字体 
    HSSFFont font = workbook.createFont(); 
    font.setColor(HSSFColor.VIOLET.index); 
    font.setFontHeightInPoints((short) 12); 
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 
    // 把字体应用到当前的样式 
    style.setFont(font); 
    // 生成并设置另一个样式 
    HSSFCellStyle style2 = workbook.createCellStyle(); 
    style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); 
    style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 
    style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); 
    style2.setBorderLeft(HSSFCellStyle.BORDER_THIN); 
    style2.setBorderRight(HSSFCellStyle.BORDER_THIN); 
    style2.setBorderTop(HSSFCellStyle.BORDER_THIN); 
    style2.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
    style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); 
    // 生成另一个字体 
    HSSFFont font2 = workbook.createFont(); 
    font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); 
    // 把字体应用到当前的样式 
    style2.setFont(font2); 
    // 声明一个画图的顶级管理器 
    HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); 
    // 定义注释的大小和位置,详见文档 
    HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5)); 
    // 设置注释内容 
    comment.setString(new HSSFRichTextString("可以在POI中添加注释!")); 
    // 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容. 
    comment.setAuthor("leno"); 

    // 产生表格标题行 
    HSSFRow row = sheet.createRow(0); 
    for (short i = 0; i < headers.length; i++) 
    { 
      HSSFCell cell = row.createCell(i); 
      cell.setCellStyle(style); 
      HSSFRichTextString text = new HSSFRichTextString(headers[i]); 
      cell.setCellValue(text); 
    } 
    // 遍历集合数据,产生数据行 
    Iterator<T> it = dataset.iterator(); 
    int index = 0; 
    while (it.hasNext()) 
    { 
      index++; 
      row = sheet.createRow(index); 
      T t = (T) it.next(); 
      // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值 
      Field[] fields = t.getClass().getDeclaredFields(); 
      for (short i = 0; i < fields.length; i++) 
      { 
        HSSFCell cell = row.createCell(i); 
        cell.setCellStyle(style2); 
        Field field = fields[i]; 
        String fieldName = field.getName(); 
        String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); 
        try 
        { 
          Class tCls = t.getClass(); 
          Method getMethod = tCls.getMethod(getMethodName, new Class[] {}); 
          Object value = getMethod.invoke(t, new Object[] {}); 
          // 判断值的类型后进行强制类型转换 
          String textValue = null; 
          if (value instanceof Boolean) 
          { 
            boolean bValue = (Boolean) value; 
            textValue = "男"; 
            if (!bValue) 
            { 
              textValue = "女"; 
            } 
          } 
          else if (value instanceof Date) 
          { 
            Date date = (Date) value; 
            SimpleDateFormat sdf = new SimpleDateFormat(pattern); 
            textValue = sdf.format(date); 
          } 
          else if (value instanceof byte[]) 
          { 
            // 有图片时,设置行高为60px; 
            row.setHeightInPoints(60); 
            // 设置图片所在列宽度为80px,注意这里单位的一个换算 
            sheet.setColumnWidth(i, (short) (35.7 * 80)); 
            // sheet.autoSizeColumn(i); 
            byte[] bsValue = (byte[]) value; 
            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,1023, 255, (short) 6, index, (short) 6, index); 
            anchor.setAnchorType(2); 
            patriarch.createPicture(anchor, workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG)); 
          } 
          else 
          { 
            // 其它数据类型都当作字符串简单处理 
            textValue = value == null? "": value.toString(); 
          } 
          // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成 
          if (textValue != null) 
          { 
            Pattern p = Pattern.compile("^//d+(//.//d+)?$"); 
            Matcher matcher = p.matcher(textValue); 
            if (matcher.matches()) 
            { 
              // 是数字当作double处理 
              cell.setCellValue(Double.parseDouble(textValue)); 
            } 
            else 
            { 
              HSSFRichTextString richString = new HSSFRichTextString(textValue); 
              HSSFFont font3 = workbook.createFont(); 
              font3.setColor(HSSFColor.BLUE.index); 
              richString.applyFont(font3); 
              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 
        { 
          // 清理资源 
        } 
      } 
    } 
  }

小结

Excel数据的导出大功告成了,个人感觉这个导出的工具类还是很好用的,希望大家能喜欢!

更多关于Java使用poi组件导出Excel格式数据文章请查看下面的相关链接

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们