1. 程式人生 > >poi 導出Excel

poi 導出Excel

建行 合並 -s org vertica pad reat 工具類 int

報表的導出是功能實現的重要的一個環節,我們今天就探究如何用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解析2003時使用的是HSSFCell,而2007的則是 XSSFCell)

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;
    }

}

poi 導出Excel