Poi實現Excel導出工具類封裝

chenlove 8年前發布 | 13K 次閱讀 Java

工具類代碼PoiExcelExport如下:

package com.myssm.util.poi;

import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Method; import java.net.URLEncoder; import java.text.DecimalFormat; import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFPalette; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellRangeAddress;

public class PoiExcelExport { HttpServletResponse response; // 文件名 private String fileName ; //文件保存路徑 private String fileDir; //sheet名 private String sheetName; //表頭字體 private String titleFontType = "Arial Unicode MS"; //表頭背景色 private String titleBackColor = "C1FBEE"; //表頭字號 private short titleFontSize = 12; //添加自動篩選的列 如 A:M private String address = ""; //正文字體 private String contentFontType = "Arial Unicode MS"; //正文字號 private short contentFontSize = 12; //Float類型數據小數位 private String floatDecimal = ".00"; //Double類型數據小數位 private String doubleDecimal = ".00"; //設置列的公式 private String colFormula[] = null;

DecimalFormat floatDecimalFormat=new DecimalFormat(floatDecimal);
DecimalFormat doubleDecimalFormat=new DecimalFormat(doubleDecimal);

private HSSFWorkbook workbook = null;

public PoiExcelExport(String fileDir,String sheetName){
     this.fileDir = fileDir;
     this.sheetName = sheetName;
     workbook = new HSSFWorkbook();
}

public PoiExcelExport(HttpServletResponse response,String fileName,String sheetName){
     this.response = response;
     this.sheetName = sheetName;
     workbook = new HSSFWorkbook();
}
/**
 * 設置表頭字體.
 * @param titleFontType
 */
public void setTitleFontType(String titleFontType) {
    this.titleFontType = titleFontType;
}
/**
 * 設置表頭背景色.
 * @param titleBackColor 十六進制
 */
public void setTitleBackColor(String titleBackColor) {
    this.titleBackColor = titleBackColor;
}
/**
 * 設置表頭字體大小.
 * @param titleFontSize
 */
public void setTitleFontSize(short titleFontSize) {
    this.titleFontSize = titleFontSize;
}
/**
 * 設置表頭自動篩選欄位,如A:AC.
 * @param address
 */
public void setAddress(String address) {
    this.address = address;
}
/**
 * 設置正文字體.
 * @param contentFontType
 */
public void setContentFontType(String contentFontType) {
    this.contentFontType = contentFontType;
}
/**
 * 設置正文字號.
 * @param contentFontSize
 */
public void setContentFontSize(short contentFontSize) {
    this.contentFontSize = contentFontSize;
}
/**
 * 設置float類型數據小數位 默認.00
 * @param doubleDecimal 如 ".00"
 */
public void setDoubleDecimal(String doubleDecimal) {
    this.doubleDecimal = doubleDecimal;
}
/**
 * 設置doubel類型數據小數位 默認.00
 * @param floatDecimalFormat 如 ".00
 */
public void setFloatDecimalFormat(DecimalFormat floatDecimalFormat) {
    this.floatDecimalFormat = floatDecimalFormat;
}
/**
 * 設置列的公式 
 * @param colFormula  存儲i-1列的公式 涉及到的行號使用@替換 如A@+B@
 */
public void setColFormula(String[] colFormula) {
    this.colFormula = colFormula;
}
/**
 * 寫excel.
 * @param titleColumn  對應bean的屬性名
 * @param titleName   excel要導出的表名
 * @param titleSize   列寬
 * @param dataList  數據
 */
public void wirteExcel(String titleColumn[],String titleName[],int titleSize[],List<?> dataList){
    //添加Worksheet(不添加sheet時生成的xls文件打開時會報錯)
    Sheet sheet = workbook.createSheet(this.sheetName);  
    //新建文件
    OutputStream out = null;
    try {    
        if(fileDir!=null){
            //有文件路徑
            out = new FileOutputStream(fileDir);                
        }else{
            //否則,直接寫到輸出流中
            out = response.getOutputStream();
            fileName = fileName+".xls";
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
        }

        //寫入excel的表頭
        Row titleNameRow = workbook.getSheet(sheetName).createRow(0); 
        //設置樣式
        HSSFCellStyle titleStyle = workbook.createCellStyle();  
        titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, titleFontType, (short) titleFontSize);
        titleStyle = (HSSFCellStyle) setColor(titleStyle, titleBackColor, (short)10);

        for(int i = 0;i < titleName.length;i++){
            sheet.setColumnWidth(i, titleSize[i]*256);    //設置寬度        
            Cell cell = titleNameRow.createCell(i);
            cell.setCellStyle(titleStyle);
            cell.setCellValue(titleName[i].toString());
        }

        //為表頭添加自動篩選
        if(!"".equals(address)){
            CellRangeAddress c = (CellRangeAddress) CellRangeAddress.valueOf(address);
            sheet.setAutoFilter(c);
        }

        //通過反射獲取數據并寫入到excel中
        if(dataList!=null&&dataList.size()>0){
            //設置樣式
            HSSFCellStyle dataStyle = workbook.createCellStyle();  
            titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, contentFontType, (short) contentFontSize);

            if(titleColumn.length>0){
                for(int rowIndex = 1;rowIndex<=dataList.size();rowIndex++){
                    Object obj = dataList.get(rowIndex-1);     //獲得該對象
                    Class clsss = obj.getClass();     //獲得該對對象的class實例
                    Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex);    
                    for(int columnIndex = 0;columnIndex<titleColumn.length;columnIndex++){
                        String title = titleColumn[columnIndex].toString().trim();
                        if(!"".equals(title)){  //字段不為空
                            //使首字母大寫
                            String UTitle = Character.toUpperCase(title.charAt(0))+ title.substring(1, title.length()); // 使其首字母大寫;
                            String methodName  = "get"+UTitle;

                            // 設置要執行的方法
                            Method method = clsss.getDeclaredMethod(methodName); 

                            //獲取返回類型
                            String returnType = method.getReturnType().getName(); 

                            String data = method.invoke(obj)==null?"":method.invoke(obj).toString();
                            Cell cell = dataRow.createCell(columnIndex);
                            if(data!=null&&!"".equals(data)){
                                if("int".equals(returnType)){
                                    cell.setCellValue(Integer.parseInt(data));
                                }else if("long".equals(returnType)){
                                    cell.setCellValue(Long.parseLong(data));
                                }else if("float".equals(returnType)){
                                    cell.setCellValue(floatDecimalFormat.format(Float.parseFloat(data)));
                                }else if("double".equals(returnType)){
                                    cell.setCellValue(doubleDecimalFormat.format(Double.parseDouble(data)));
                                }else{
                                    cell.setCellValue(data);
                                }
                            }
                        }else{   //字段為空 檢查該列是否是公式
                            if(colFormula!=null){
                                String sixBuf = colFormula[columnIndex].replace("@", (rowIndex+1)+"");
                                Cell cell = dataRow.createCell(columnIndex);
                                cell.setCellFormula(sixBuf.toString());
                            }
                        }
                    }
                }

            }
        }

        workbook.write(out);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {  
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }  
}

/**
 * 將16進制的顏色代碼寫入樣式中來設置顏色
 * @param style  保證style統一
 * @param color 顏色:66FFDD
 * @param index 索引 8-64 使用時不可重復
 * @return
 */
public CellStyle setColor(CellStyle style,String color,short index){
    if(color!=""&&color!=null){
        //轉為RGB碼
        int r = Integer.parseInt((color.substring(0,2)),16);   //轉為16進制
        int g = Integer.parseInt((color.substring(2,4)),16);
        int b = Integer.parseInt((color.substring(4,6)),16);
        //自定義cell顏色
        HSSFPalette palette = workbook.getCustomPalette(); 
        palette.setColorAtIndex((short)index, (byte) r, (byte) g, (byte) b);

        style.setFillPattern(CellStyle.SOLID_FOREGROUND); 
        style.setFillForegroundColor(index);
    }
    return style;   
}

/**
 * 設置字體并加外邊框
 * @param style  樣式
 * @param style  字體名
 * @param style  大小
 * @return
 */
public CellStyle setFontAndBorder(CellStyle style,String fontName,short size){
    HSSFFont font = workbook.createFont();  
    font.setFontHeightInPoints(size);    
    font.setFontName(fontName); 
    font.setBold(true);
    style.setFont(font);
    style.setBorderBottom(CellStyle.BORDER_THIN); //下邊框    
    style.setBorderLeft(CellStyle.BORDER_THIN);//左邊框    
    style.setBorderTop(CellStyle.BORDER_THIN);//上邊框    
    style.setBorderRight(CellStyle.BORDER_THIN);//右邊框   
    return style;
}
/**
 * 刪除文件
 * @param fileDir
 * @return
 */
public boolean deleteExcel(){
    boolean flag = false;
    File file = new File(this.fileDir);
    // 判斷目錄或文件是否存在  
    if (!file.exists()) {  // 不存在返回 false  
        return flag;  
    } else {  
        // 判斷是否為文件  
        if (file.isFile()) {  // 為文件時調用刪除文件方法  
            file.delete();
            flag = true;
        } 
    }
    return flag;
}
/**
 * 刪除文件
 * @param fileDir
 * @return
 */
public boolean deleteExcel(String path){
    boolean flag = false;
    File file = new File(path);
    // 判斷目錄或文件是否存在  
    if (!file.exists()) {  // 不存在返回 false  
        return flag;  
    } else {  
        // 判斷是否為文件  
        if (file.isFile()) {  // 為文件時調用刪除文件方法  
            file.delete();
            flag = true;
        } 
    }
    return flag;
}

}</pre>
測試如下:

實體bean:

package com.myssm.util.poi;

public class Man { private String name; private int sex; private String idCard; private float salary; public Man(String name, int sex, String idCard, float salary) { super(); this.name = name; this.sex = sex; this.idCard = idCard; this.salary = salary; }

public Man() {
    super();
}

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getSex() {
    return sex;
}
public void setSex(int sex) {
    this.sex = sex;
}
public String getIdCard() {
    return idCard;
}
public void setIdCard(String idCard) {
    this.idCard = idCard;
}
public float getSalary() {
    return salary;
}
public void setSalary(float salary) {
    this.salary = salary;
}


}</pre> 測試類:

package com.myssm.util.poi;

import java.util.ArrayList; import java.util.List;

public class Test {

public static void main(String[] args) {
    PoiExcelExport pee = new PoiExcelExport("E:/test.xls","sheet1");
    //數據
    List<Man> dataList = new ArrayList();
    Man man1 = new Man("張三",20,"男",(float)10000.8);
    Man man2 = new Man("李四",21,"男",(float)11000.8);
    Man man3 = new Man("王五",22,"女",(float)1200.8);
    Man man4 = new Man("趙六",23,"男",(float)13000.8);
    Man man5 = new Man("田七",24,"男",(float)14000.8);
    Man man6 = new Man();
    man6.setName("老八");
    dataList.add(man1);dataList.add(man2);dataList.add(man3);dataList.add(man4);dataList.add(man5);
    dataList.add(man6);
    //調用
    String titleColumn[] = {"name","sex","idCard","salary",""};
    String titleName[] = {"姓名","性別","身份證號","月薪","年薪"};
    int titleSize[] = {13,13,13,13,13};
    //其他設置 set方法可全不調用
    String colFormula[] = new String[5];
    colFormula[4] = "D@*12";   //設置第5列的公式
    pee.setColFormula(colFormula);
    pee.setAddress("A:D");  //自動篩選 

    pee.wirteExcel(titleColumn, titleName, titleSize, dataList);
}

}</pre>


 本文由用戶 chenlove 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!