POI 生成Excel表格的使用

时间:2020-03-24
本文章向大家介绍POI 生成Excel表格的使用,主要包括POI 生成Excel表格的使用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一.简介

Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

  结构:
    • HSSF - 提供读写Microsoft Excel格式档案的功能。
    • XSSF - 提供读写Microsoft Excel OOXML格式档案的功能。
    • HWPF - 提供读写Microsoft Word格式档案的功能。
    • HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
    • HDGF - 提供读写Microsoft Visio格式档案的功能。

二.POI生成Excel表格

  在POI中,使用面向对象的思想将表格中的工作簿、表、行、单元格、样式等都封装为类,读写这些内容就是对这些类的操作

public class ExportExcelUtils {
    public static ByteArrayOutputStream exportCustomerExcel(List<Customer> customers, String sheetName) {
        // 一组装excel文档
        // 1,创建工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 2,创建样式
        HSSFCellStyle baseStyle = ExportHSSFCellStyle.createBaseStyle(workbook);
        HSSFCellStyle subTitleStyle = ExportHSSFCellStyle.createSubTitleStyle(workbook);
        HSSFCellStyle tableTitleStyle = ExportHSSFCellStyle.createTableTitleStyle(workbook);
        HSSFCellStyle titleStyle = ExportHSSFCellStyle.createTitleStyle(workbook);
        // 3在工作簿创建sheet
        HSSFSheet sheet = workbook.createSheet(sheetName);
        // 4,设置sheet
        sheet.setDefaultColumnWidth(25);
        // 5,合并
        CellRangeAddress region1 = new CellRangeAddress(0, 0, 0, 6);
        CellRangeAddress region2 = new CellRangeAddress(1, 1, 0, 6);
        sheet.addMergedRegion(region1);
        sheet.addMergedRegion(region2);
        // 6,创建第一行
        int index = 0;
        HSSFRow row1 = sheet.createRow(index);
        // 6.1在第一行里面创建一个单元格
        HSSFCell row1_cell1 = row1.createCell(0);
        // 6.2设置标题样式
        row1_cell1.setCellStyle(titleStyle);
        // 6.3设置单元格内容
        row1_cell1.setCellValue("客户数据列表");

        // 7,第二行
        index++;
        HSSFRow row2 = sheet.createRow(index);
        // 7.1在第一行里面创建一个单元格
        HSSFCell row2_cell1 = row2.createCell(0);
        // 7.2设置标题样式
        row2_cell1.setCellStyle(subTitleStyle);
        // 7.3设置单元格内容
        row2_cell1.setCellValue("总条数:" + customers.size() + "   导出时间:" + new Date().toLocaleString());

        // 8第三行
        String[] titles = { "身份证号", "客户姓名", "客户电话", "客户地址", "客户职位", "性别", "录入时间" };
        index++;
        HSSFRow row3 = sheet.createRow(index);
        for (int i = 0; i < titles.length; i++) {
            HSSFCell row3_cell = row3.createCell(i);
            row3_cell.setCellStyle(tableTitleStyle);
            row3_cell.setCellValue(titles[i]);
        }
        // 9第四行
        for (int i = 0; i < customers.size(); i++) {
            index++;
            Customer customer = customers.get(i);
            HSSFRow row = sheet.createRow(index);
            // 9.1创建列身份证号
            HSSFCell row_identity = row.createCell(0);
            row_identity.setCellStyle(baseStyle);
            row_identity.setCellValue(customer.getIdentity());
            // 9.2创建列客户姓名
            HSSFCell row_custname = row.createCell(1);
            row_custname.setCellStyle(baseStyle);
            row_custname.setCellValue(customer.getCustname());
            // 9.3创建列客户电话
            HSSFCell row_phone = row.createCell(2);
            row_phone.setCellStyle(baseStyle);
            row_phone.setCellValue(customer.getPhone());
            // 9.4创建列客户地址
            HSSFCell row_address = row.createCell(3);
            row_address.setCellStyle(baseStyle);
            row_address.setCellValue(customer.getAddress());
            // 9.5创建列客户职位
            HSSFCell row_career = row.createCell(4);
            row_career.setCellStyle(baseStyle);
            row_career.setCellValue(customer.getCareer());
            // 9.6创建列性别
            HSSFCell row_sex = row.createCell(5);
            row_sex.setCellStyle(baseStyle);
            row_sex.setCellValue(customer.getGender() == 1 ? "男" : "女");
            // 9.7创建列录入时间
            HSSFCell row_createtime = row.createCell(6);
            row_createtime.setCellStyle(baseStyle);
            row_createtime.setCellValue(customer.getCreatetime().toLocaleString());
        }
        // 到此excel组装完成

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 把workbook里面的数据写到outputStream
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputStream;

    }
}
package com.sd.stat.util;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;

public class ExportHSSFCellStyle {
    /**
     * 创建基础样式  
     * 水平和垂直居中
     */
    public static HSSFCellStyle  createBaseStyle(HSSFWorkbook workbook) {
        HSSFCellStyle style = workbook.createCellStyle();
        //设置水平居中
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }
    
    /**
     * 创建数据表格的头的样式 
     */
    public static HSSFCellStyle createTableTitleStyle(HSSFWorkbook workbook) {
        HSSFCellStyle style = createBaseStyle(workbook);
        
        //设置字体
        HSSFFont font=workbook.createFont();
        font.setBold(true);//是否加粗
        font.setItalic(false);//是否斜体
        font.setFontHeightInPoints((short)10); //设置字体大小
        font.setColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());//设置颜色
        font.setFontName("黑体");//设置字体
        style.setFont(font);
        
        return style;
    }
    
    
    /**
     * 创建小标题样式
     */
    public static HSSFCellStyle createSubTitleStyle(HSSFWorkbook workbook) {
        HSSFCellStyle style = createBaseStyle(workbook);
        //设置右对齐
        style.setAlignment(HorizontalAlignment.RIGHT);
        //设置字体
        HSSFFont font=workbook.createFont();
        font.setBold(true);//是否加粗
        font.setFontHeightInPoints((short)12); //设置字体大小
        font.setColor(HSSFColor.HSSFColorPredefined.BLUE_GREY.getIndex());//设置颜色
        font.setFontName("黑体");//设置字体
        style.setFont(font);
        return style;
    }
    
    
    
    /**
     * 创建标题样式
     */
    public static HSSFCellStyle createTitleStyle(HSSFWorkbook workbook) {
        HSSFCellStyle style = createBaseStyle(workbook);
        //设置字体
        HSSFFont font=workbook.createFont();
        font.setBold(true);//是否加粗
        font.setFontHeightInPoints((short)26); //设置字体大小
        font.setColor(HSSFColor.HSSFColorPredefined.DARK_RED.getIndex());//设置颜色
        font.setFontName("宋体");//设置字体
        style.setFont(font);
        return style;
    }
    
}

Web应用中将数据生成Excel表并返回客户端:

  请求➡后台查询数据➡POI工具类生成workbook以流的形式返回➡Controller返回ResponseEntity,设置响应形式,workbook的字节流转换为字节数据

  图片,数据表格等多媒体数据返回➡以字节流的形式传输,最后转换为Byte数组传输给ResponseEntity

    @RequestMapping("exportCustomerExcel.do")
    public ResponseEntity<Object> exportCustomerExcel(CustomerVo customerVo,HttpServletResponse response){
        //调用Service层查询数据List+数据表名称
        List<Customer> customers = customerService.queryNomalCustomer(customerVo);
        String fileName="客户数据.xls";
        String sheetName = "客户数据";
        //调用POI工具类导出Excel表数据-->表格数据转化为流运输过来
        ByteArrayOutputStream customerExcel = ExportExcelUtils.exportCustomerExcel(customers, sheetName);
        //设置响应信息包装为ResponseEntity返回
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");//处理响应文件名乱码问题
            //设置响应头
            HttpHeaders headers = new HttpHeaders();
            //封装响应内容类型(APPLICATION_OCTET_STREAM 响应的内容不限定)
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //设置下载文件的名称
            headers.setContentDispositionFormData("attachment", fileName);
            //再将字节流转化为具体的字节数据
            return new ResponseEntity<Object>(customerExcel.toByteArray(), headers,HttpStatus.CREATED);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

  

原文地址:https://www.cnblogs.com/autism-dong/p/12559598.html