poi 导出Excel

报表的导出是功能实现的重要的一个环节,我们今天就探究如何用poi 实现报表的导出Excel 

1引入poi   

  <!--poi begin-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-excelant</artifactId>
            <version>${poi.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-examples</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <!--end-->

2 选择导出的Excel 是什么格式的,这里我们选择Excel 2003 的(Poi解析2007年前的Excel时使用的是HSSFCell(.xls),而2007后的则是 XSSFCell(.xlsx))

2.1 创建文档

 HSSFWorkbook wb = new HSSFWorkbook();

2.2 创建文档的样式

//创建样式对象
HSSFCellStyle style=wb.createCellStyle(); //创建字体对象 HSSFFont font=wb.createFont(); //设置为宋体 font.setFontName("宋体"); //设置字体大小 font.setFontHeightInPoints((short)10); //左边框 style.setBorderLeft(BorderStyle.THIN);   //右边框 style.setBorderRight(BorderStyle.THIN); //上边框 style.setBorderTop(BorderStyle.THIN); //下边框 style.setBorderBottom(BorderStyle.THIN); //垂直居中 style.setVerticalAlignment(VerticalAlignment.CENTER); //字体居中 注://style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中--废弃
style.setAlignment(HorizontalAlignment.CENTER);
//样式字体
style.setFont(font);
//自动换行
style.setWrapText(
true);
      //单元格不锁定
style.setLocked(
false);

2.3 创建表格  注意 行列从0 开始 

 //创建sheet
HSSFSheet sheet = wb.createSheet();

 //合并单元格

 //合并单元格(必须先合并在创建行列) 参数 --开始行,结束行,开始列,结束列    
sheet.addMergedRegion(new CellRangeAddress(2, 3, 0, 4)); sheet.addMergedRegion(new CellRangeAddress(4, 4, 0, 1));

 //设置行列(合并的单元格只用创建赋值第一个单元格就可以了)

(合并的单元格只用创建赋值第一个单元格就可以了)
//创建第三行
HSSFRow row2 = sheet.createRow(2);
//创建第三行第一列 HSSFCell cell2q0
= row2.createCell(0);
//赋值 cell2q0.setCellValue(
"报表");
//为这个单元格设置样式
cell2q0.setCellStyle(style);

 //设置行高宽

//设置第0 行列的高宽
sheet.setColumnWidth(0, 20*256); row=sheet.getRow(0); row.setHeight((short) (20*20));

 //打印

HSSFPrintSetup print = sheet.getPrintSetup();

        print.setLandscape(true);

        print.setScale((short) 80);

        print.setFitHeight((short) 4);

        print.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);

        String filename = 报表.xls";

        ExeclUtils.getFile(response, wb, filename);

 3 ExeclUtils 工具类

package com.prison.common.poi;

import com.prison.common.util.ImageHelper;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;

public class ExeclUtils {
    
    
    public static HSSFCellStyle getStyle(HSSFWorkbook wb) {
        
        
        HSSFCellStyle style=wb.createCellStyle();
        
        HSSFFont font=wb.createFont();
        
        font.setFontName("宋体");
        
        font.setFontHeightInPoints((short)10);
         
        style.setBorderLeft(BorderStyle.THIN);
        
        style.setBorderRight(BorderStyle.THIN);
        
        style.setBorderTop(BorderStyle.THIN);
        
        style.setBorderBottom(BorderStyle.THIN);
        
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        
        style.setAlignment(HorizontalAlignment.CENTER);
        
        style.setFont(font);
        
        style.setWrapText(true);
        
        style.setLocked(false);
        
        return style;
    }
    
    public static HSSFCellStyle getCellStyle(HSSFWorkbook wb, int fontSize, int align, int verticalAlign) {
        
        
        HSSFCellStyle style=wb.createCellStyle();
        
        HSSFFont font=wb.createFont();
        
        font.setFontName("宋体");
        
        font.setFontHeightInPoints((short)10);
         
        style.setBorderLeft(BorderStyle.THIN);
        
        style.setBorderRight(BorderStyle.THIN);
        
        style.setBorderTop(BorderStyle.THIN);
        
        style.setBorderBottom(BorderStyle.THIN);
        
        switch (align) {
            case 1:
                style.setAlignment(HorizontalAlignment.LEFT);
                break;
            case 2:
                style.setAlignment(HorizontalAlignment.CENTER);
                break;
    
            default:
                style.setAlignment(HorizontalAlignment.RIGHT);
                break;
        }
        
        switch (align) {
            case 1:
                style.setVerticalAlignment(VerticalAlignment.TOP);
                break;
            case 2:
                style.setVerticalAlignment(VerticalAlignment.CENTER);
                break;
    
            default:
                style.setVerticalAlignment(VerticalAlignment.BOTTOM);
                break;
        }
        
        style.setFont(font);
        
        style.setWrapText(true);
        
        style.setLocked(false);
        
        return style;
    }
    
    
    
    
    
    public static  void setcellStyle(HSSFCellStyle style, int endColNum, HSSFSheet sheet, int beginRowNum, int endRowNum, HashMap<Integer, String[]> map) {
        String[] str;
        
        HSSFCell cell;
        
        HSSFRow row;
        for (int i=beginRowNum;i<endRowNum;i++) {
            row=sheet.createRow(i);
            str=map.get(i);
            for(int j=0;j<endColNum;j++) {
                cell=row.createCell(j);
                cell.setCellStyle(style);
                if (str!=null&&str.length>j) {
                    cell.setCellValue(str[j]);
                }else {
                    cell.setCellValue("");
                }
            }
        }
        
    }
    
    
    public static  void setSpecialCellStyle(HSSFCellStyle style, int rowNum, HSSFSheet sheet, int colNum) {
        
        HSSFCell cell;
        
        HSSFRow row;
        
        row =sheet.getRow(rowNum);
        
        cell=row.getCell(colNum);
        
        cell.setCellStyle(style);
        
        cell.setCellValue(cell.getStringCellValue());
        
        
    }
    
    
    
    public static void setWidth(HSSFSheet sheet, int colNum, int width) {
        
        for(int i=0;i<colNum;i++) {
            sheet.setColumnWidth(i, width*256);
        }
    }
    
    public static void setCellMerge(HSSFSheet sheet, String[] str) {
        
        for(int i=0;i<str.length;i++) {
            sheet.addMergedRegion(CellRangeAddress.valueOf(str[i]));
        }
        
    }
    
    public static void setRowHeight(HSSFSheet sheet, int beginRowNum, int endRowNum, int height) {
        
        HSSFRow row ;
        for(int i=beginRowNum;i<endRowNum;i++) {
            
             row=sheet.getRow(i);
             
             row.setHeight((short) (height*20));
            
        }
        
    }
    
    public static void setCellWidth(HSSFSheet sheet, int beginCelNum, int endCelNum, int width) {
        
        for(int i=beginCelNum;i<endCelNum;i++) {
            
            sheet.setColumnWidth(i, width*256);
            
        }
        
    }
    
    
    
    public static void getFile(HttpServletResponse response, HSSFWorkbook wb , String fileName) {
        
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        ServletOutputStream out=null;
        InputStream is=null;
        ByteArrayOutputStream os=null;
        
        try {
            String filename=fileName;
            
            response.setContentType("application/vnd.ms-excel;charset=utf-8");  
            response.addHeader("Content-Disposition", "attachment;filename=" + new String((filename).getBytes(), "iso-8859-1") );
            
            os= new ByteArrayOutputStream();
            wb.write(os);
            byte[] content = os.toByteArray();
            is = new ByteArrayInputStream(content);
            out = response.getOutputStream();     
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
              bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            ImageHelper.closeIO(bis,bos);
            ImageHelper.closeIO(is,os);
            ImageHelper.closeIO(null,out);
        } 
        
    }
    
    
    
    public static XSSFCellStyle getXSSFStyle(XSSFWorkbook wb) {
        XSSFCellStyle style=wb.createCellStyle();
        
        XSSFFont font=wb.createFont();
        
        font.setFontName("宋体");
        
        font.setFontHeightInPoints((short)12);
         
        style.setBorderLeft(BorderStyle.THIN);
        
        style.setBorderRight(BorderStyle.THIN);
        
        style.setBorderTop(BorderStyle.THIN);
        
        style.setBorderBottom(BorderStyle.THIN);
        
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        
        style.setAlignment(HorizontalAlignment.CENTER);
        
        style.setFont(font);
        
        style.setWrapText(true);
        
        style.setLocked(false);
        
        return style;
    }

}
原文地址:https://www.cnblogs.com/jsbk/p/9752981.html