util之ExportExcelUtil (excel導出工具類 poi 4.0.1)


 簡潔版

package com.xxx.xxx.platform.util;

import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;


/**
 * excel導出工具類 poi 4.0.1
 */
public class ExportExcelUtil {

    /**
     * @param request
     * @param response
     * @param wb
     * @param fileName 自定義導出的文件取名(導出后文件名叫什么)
     * @throws Exception
     *   調用后瀏覽器自動生成excel
     */
    public static void exportExcel(HttpServletRequest request, HttpServletResponse response, HSSFWorkbook wb, String fileName) throws Exception {

        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GB2312"), "8859_1"));
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        OutputStream out = response.getOutputStream();
        wb.write(out);
        out.flush();
        out.close();
    }

    /**
     *
     * @param title 標題
     * 
     * @param headers 表頭 
     * 使用方法: String[] headers = {"序號","單位","機組","容量","開始","結束","工期","類型","發電類型"}; 
     *  
     * @param values 表中元素
     * 使用方法:
     *      String[][] values = new String[query.size()][headers.length];
     *   for (int i = 0; i < query.size(); i++) {
     *       Jzjxjh e = query.get(i);
     *       values[i][0]=e.getXh()+"";
     *       values[i][1]=e.getDw();
     *       values[i][2]=e.getJz();
     *       values[i][3]=e.getRl()+"";
     *       values[i][4]=sdf.format(e.getKs());
     *   }
     * 
     * @param columnWidth 每一列的寬度
     * 使用方法:  轉入null 或者     int[] columnWidth={18,18,18,18,20,20,18,18,18};
     * 
     * @return 返回 HSSFWorkbook  wb
     */
    public static HSSFWorkbook getHSSFWorkbook(String title, String headers[], String[][] values,Integer[] columnWidth) throws Exception {

        // 創建一個HSSFWorkbook,對應一個Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        // 在workbook中添加一個sheet,對應Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(title);
        
        // 創建標題合並行
        sheet.addMergedRegion(new CellRangeAddress(0, (short) 0, 0, (short) headers.length - 1));

        HSSFCellStyle style = getTitleStyle(wb);
        // 設置標題字體
        Font titleFont = getTitleFont(wb);
        //設置粗體
//        titleFont.setBold(true);
        style.setFont(titleFont);

        // 設置表內容樣式
        // 創建單元格,並設置值表頭 設置表頭居中
        HSSFCellStyle style1 = getContextStyle(wb);

        // 產生標題行
        HSSFRow hssfRow = sheet.createRow(0);
        HSSFCell cell = hssfRow.createCell(0);
        cell.setCellValue(title);
        cell.setCellStyle(style);


        
        // 產生表頭
        HSSFCellStyle hssfCellStyle = getHeadStyle(wb);
        HSSFRow row1 = sheet.createRow(1);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell hssfCell = row1.createCell(i);
            hssfCell.setCellValue(headers[i]);
            hssfCell.setCellStyle(hssfCellStyle);
        }
        //自適應列寬度(實際效果並不理想)
//        sheet.autoSizeColumn(1);

        //設置表頭寬度
        if(columnWidth!=null&&columnWidth.length>0){
            for(int i =0;i<columnWidth.length;i++){
                  sheet.setColumnWidth(i, columnWidth[i]*256);
            }
        }
        
        // 創建內容
        for (int i = 0; i < values.length; i++) {
            row1 = sheet.createRow(i + 2);
            for (int j = 0; j < values[i].length; j++) {
                // 將內容按順序賦給對應列對象
                HSSFCell hssfCell = row1.createCell(j);
                hssfCell.setCellValue(values[i][j]);
                hssfCell.setCellStyle(style1);
            }
        }
        return wb;
    }

    /**
     * @param wb
     * @return 設置表內容樣式 創建單元格,並設置值表頭 設置表頭居中
     */
    private static HSSFCellStyle getContextStyle(HSSFWorkbook wb) throws Exception {
        HSSFCellStyle style1 = wb.createCellStyle();
        style1.setBorderBottom(BorderStyle.THIN);
        style1.setBorderLeft(BorderStyle.THIN);
        style1.setBorderRight(BorderStyle.THIN);
        style1.setBorderTop(BorderStyle.THIN);
        return style1;
    }

    /**
     * @param wb
     * @return 設置標題字體
     */
    private static Font getTitleFont(HSSFWorkbook wb) throws Exception {
        Font titleFont = wb.createFont();
        titleFont.setFontHeightInPoints((short) 14);
        return titleFont;
    }

    /**
     * @param wb
     * @return 設置標題樣式
     */
    private static HSSFCellStyle getTitleStyle(HSSFWorkbook wb) throws Exception {
        // 設置標題樣式
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 設置居中樣式
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }

    /**
     * @param wb
     * @return 設置值表頭樣式 設置表頭居中
     */
    private static HSSFCellStyle getHeadStyle(HSSFWorkbook wb) throws Exception {
        // 設置值表頭樣式 設置表頭居中
        HSSFCellStyle hssfCellStyle = wb.createCellStyle();
        hssfCellStyle.setAlignment(HorizontalAlignment.CENTER); // 設置居中樣式
        hssfCellStyle.setBorderBottom(BorderStyle.THIN);
        hssfCellStyle.setBorderLeft(BorderStyle.THIN);
        hssfCellStyle.setBorderRight(BorderStyle.THIN);
        hssfCellStyle.setBorderTop(BorderStyle.THIN);
        return hssfCellStyle;
    }

}
View Code

 

優化精進版

package com.xxx.xxx.platform.util;

import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;


/**
 * excel導出工具類 poi 4.0.1
 */
public class ExpTest {

    /**
     * @param request
     * @param response
     * @param wb
     * @param fileName 自定義導出的文件取名(導出后文件名叫什么)
     * @throws Exception
     *   調用后瀏覽器自動生成excel
     */
    public static void exportExcel(HttpServletRequest request, HttpServletResponse response, HSSFWorkbook wb, String fileName) throws Exception {

        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GB2312"), "8859_1"));
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        OutputStream out = response.getOutputStream();
        wb.write(out);
        out.flush();
        out.close();
    }

    /**
     * @param wb (轉入的HSSFWorkbook 如果為空則自動創建)
     * @param needForTitle 是否需要標題 (即第一行是否需要合並作為標題,如果不需要輸入false,輸入null默認為需要)
     * @param title 標題 (第一行合並的單元格的內容)
     * @param headers 表頭  (每一列字段中文說明)
     * 使用方法: 
     * String[] headers = {"序號","單位","機組","容量","開始","結束","工期","類型","發電類型"}; 
     *  
     * @param values 表中元素    ( 二維數組,第一維表示記錄數即每一行,第二維表示列 也是java實體類的屬性值)
     * 使用方法:
     * (實例化操作可以直接get賦值如下,也可以通過java反射機制)
     *      String[][] values = new String[query.size()][headers.length];
     *   for (int i = 0; i < query.size(); i++) {
     *       Jzjxjh e = query.get(i);
     *       values[i][0]=e.getXh()+"";
     *       values[i][1]=e.getDw();
     *       values[i][2]=e.getJz();
     *       values[i][3]=e.getRl()+"";
     *       values[i][4]=sdf.format(e.getKs());
     *   }
     * 
     * @param columnWidth 每一列的寬度
     * 使用方法:  轉入null 或者     int[] columnWidth={18,18,18,18,20,20,18,18,18};
     * 
     * @return 返回 HSSFWorkbook  wb
     */
    public static HSSFWorkbook getHSSFWorkbook(HSSFWorkbook wb,Boolean needForTitle,String title, String headers[], String[][] values,Integer[] columnWidth) throws Exception {

        //默認行操作從第一行開始
        int curRow = 0;
        
        if(wb==null){
            // 創建一個HSSFWorkbook,對應一個Excel文件
             wb = new HSSFWorkbook();
        }

        // 在workbook中添加一個sheet,對應Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(title);
        
        if(needForTitle==true||needForTitle==null){
            curRow = createTitle(wb,sheet,curRow,title,headers);
        }

        curRow = createHeader(wb, sheet, curRow, headers, columnWidth);
        
        curRow = createContent(wb, sheet, curRow, values);
        
        return wb;
    }

    /**
     * @param wb
     * @param sheet
     * @param curRow
     * @param values
     * @return 產生表數據
     * @throws Exception
     */
    private static int createContent(HSSFWorkbook wb, HSSFSheet sheet, int curRow, String[][] values) throws Exception {
        // 創建單元格,內容樣式 
        HSSFCellStyle contentStyle = getContextStyle(wb);

        // 創建內容
        for (int i = 0; i < values.length; i++) {
            HSSFRow contentRow = sheet.createRow(curRow++);
            for (int j = 0; j < values[i].length; j++) {
                // 將內容按順序賦給對應列對象
                HSSFCell hssfCell = contentRow.createCell(j);
                hssfCell.setCellValue(values[i][j]);
                hssfCell.setCellStyle(contentStyle);
            }
        }
        return curRow;
    }

    /**
     * @param wb
     * @param sheet
     * @param curRow
     * @param headers
     * @param columnWidth
     * @return 產生表頭
     * @throws Exception
     */
    private static int createHeader(HSSFWorkbook wb, HSSFSheet sheet, int curRow, String[] headers, Integer[] columnWidth) throws Exception {
        // 產生表頭
        HSSFCellStyle headerStyle = getHeadStyle(wb);
        HSSFRow headerRow = sheet.createRow(curRow++);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell hssfCell = headerRow.createCell(i);
            hssfCell.setCellValue(headers[i]);
            hssfCell.setCellStyle(headerStyle);
        }
        //自適應列寬度(實際效果並不理想)
//        sheet.autoSizeColumn(1);

        //設置表頭寬度
        if(columnWidth!=null&&columnWidth.length>0){
            for(int i =0;i<columnWidth.length;i++){
                  sheet.setColumnWidth(i, columnWidth[i]*256);
            }
        }
        return curRow;
    }

    /**
     * @param wb
     * @param title
     * @param headers
     * @param curRow
     * @param sheet
     * @return 創建標題行 后 行數據會+1並返回 行數
     * @throws Exception
     */
    private static int createTitle(HSSFWorkbook wb, HSSFSheet sheet, int curRow, String title, String[] headers) throws Exception {
        // 創建標題合並行
        sheet.addMergedRegion(new CellRangeAddress(0, (short) 0, 0, (short) headers.length - 1));
        HSSFCellStyle style = getTitleStyle(wb);
        // 設置標題字體
        Font titleFont = getTitleFont(wb);
        //設置粗體
        // titleFont.setBold(true);
        style.setFont(titleFont);
        
        // 產生標題行
        HSSFRow hssfRow = sheet.createRow(curRow++);
        HSSFCell cell = hssfRow.createCell(0);
        cell.setCellValue(title);
        cell.setCellStyle(style);
        return curRow;
    }

    /**
     * @param wb
     * @return 設置表內容樣式 創建單元格,並設置值表頭 設置表頭居中
     */
    private static HSSFCellStyle getContextStyle(HSSFWorkbook wb) throws Exception {
        HSSFCellStyle style1 = wb.createCellStyle();
        style1.setBorderBottom(BorderStyle.THIN);
        style1.setBorderLeft(BorderStyle.THIN);
        style1.setBorderRight(BorderStyle.THIN);
        style1.setBorderTop(BorderStyle.THIN);
        return style1;
    }

    /**
     * @param wb
     * @return 設置標題字體
     */
    private static Font getTitleFont(HSSFWorkbook wb) throws Exception {
        Font titleFont = wb.createFont();
        titleFont.setFontHeightInPoints((short) 14);
        return titleFont;
    }

    /**
     * @param wb
     * @return 設置標題樣式
     */
    private static HSSFCellStyle getTitleStyle(HSSFWorkbook wb) throws Exception {
        // 設置標題樣式
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 設置居中樣式
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }

    /**
     * @param wb
     * @return 設置值表頭樣式 設置表頭居中
     */
    private static HSSFCellStyle getHeadStyle(HSSFWorkbook wb) throws Exception {
        // 設置值表頭樣式 設置表頭居中
        HSSFCellStyle hssfCellStyle = wb.createCellStyle();
        hssfCellStyle.setAlignment(HorizontalAlignment.CENTER); // 設置居中樣式
        hssfCellStyle.setBorderBottom(BorderStyle.THIN);
        hssfCellStyle.setBorderLeft(BorderStyle.THIN);
        hssfCellStyle.setBorderRight(BorderStyle.THIN);
        hssfCellStyle.setBorderTop(BorderStyle.THIN);
        return hssfCellStyle;
    }

}
View Code

 

添加一個方法,可以傳入cell返回一個string類型值

//獲取單元格各類型值,返回字符串類型
    public static String getCellValueByCell(Cell cell) {
        //判斷是否為null或空串
        if (cell == null || cell.toString().trim().equals("")) {
            return "";
        }
        String cellValue = "";
        CellType cellTypeEnum = cell.getCellTypeEnum();
        switch (cellTypeEnum) {
            case NUMERIC: // 數字
                short format = cell.getCellStyle().getDataFormat();
                if (DateUtil.isCellDateFormatted(cell)) {
                    SimpleDateFormat sdf;
                    //System.out.println("cell.getCellStyle().getDataFormat()="+cell.getCellStyle().getDataFormat());
                    if (format == 20 || format == 32) {
                        sdf = new SimpleDateFormat("HH:mm");
                    } else if (format == 14 || format == 31 || format == 57 || format == 58) {
                        // 處理自定義日期格式:m月d日(通過判斷單元格的格式id解決,id的值是58)
                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                        double value = cell.getNumericCellValue();
                        Date date = org.apache.poi.ss.usermodel.DateUtil
                                .getJavaDate(value);
                        cellValue = sdf.format(date);
                    } else {// 日期
                        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    }
                    try {
                        cellValue = sdf.format(cell.getDateCellValue());// 日期
                    } catch (Exception e) {
                        try {
                            throw new Exception("exception on get date data !".concat(e.toString()));
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    } finally {
                        sdf = null;
                    }
                } else {
                    BigDecimal bd = BigDecimal.valueOf(cell.getNumericCellValue());
                    cellValue = bd.toPlainString();// 數值 這種用BigDecimal包裝再獲取plainString,可以防止獲取到科學計數值
                }
                break;
            case STRING: // 字符串
                cellValue = cell.getStringCellValue();
                break;
            case BOOLEAN: // Boolean
                cellValue = cell.getBooleanCellValue() + "";
                break;
            case FORMULA: // 公式
                cellValue = cell.getCellFormula();
                break;
            case BLANK: // 空值
                cellValue = "";
                break;
            case ERROR: // 故障
                cellValue = "ERROR VALUE";
                break;
            default:
                cellValue = "UNKNOW VALUE";
                break;
        }
        return cellValue;
    }
傳入cell返回string

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM