導出帶樣式的Excel功能模塊的實現

開發後臺系統的過程當中,經常有導出Excel的需求,雖然程序早已上線,閒暇之時也覺應總結。有關更多POI的文檔資料,參考http://poi.apache.org/。Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供給Java程式對Microsoft Office格式檔案讀和寫的功能。HSSF提供讀寫Mircosoft Excel XLS格式檔案的功能,HSSF是Horrible(可怕的) Spreadsheet(電子表格) Format的縮寫。是在JSP頁面中添加以下Code:html

<input type="button" id="exportExcel" style="height:30px; width:70px; background-color:#159BE6; float:right; margin:4px 5px 0 0;" value="導出EXCEL"></input>

前端頁面顯示一個如圖所示的按鈕:前端

而後添加JS代碼:java

<script>
    $(document).ready(function(){
        $("#exportExcel").click(function(){
            var spId = ${spId};
            var addTimeStart = '<fmt:formatDate value="${addTimeStart}" pattern="yyyy-MM-dd" />';
            var addTimeEnd = '<fmt:formatDate value="${addTimeEnd}" pattern="yyyy-MM-dd" />';
            var url="/complaint/export_excel.do?";
            url += "spId="+spId;
            url += "&addTimeStart=" +addTimeStart;
            url += "&addTimeEnd=" + addTimeEnd;
            window.location.href=url;
        })
    })
</script>

在控制層中添加以下Java代碼:apache

@RequestMapping(value = "/complaint/export_excel")
    public void exportExcel(HttpServletResponse _response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook(); //生成Excel工做薄
        Map<String, CellStyle> style = createStyles(workbook);
        HSSFSheet sheet = workbook.createSheet("通道平均信息分析報表"); //生成工做表
        sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$F$1")); //合併單元格
        sheet.setDefaultColumnWidth(25); //設置默認列寬度
        
        HSSFRow row0 = sheet.createRow(0);
        HSSFCell titleCell = row0.createCell(0);
        titleCell.setCellValue("通道平均信息分析報表");
        titleCell.setCellStyle(style.get("title"));
        HSSFRow row1 = sheet.createRow(1);
        HSSFCell headerCell0 = row1.createCell(0);
        headerCell0.setCellValue("時間");
        headerCell0.setCellStyle(style.get("header"));
        HSSFCell headerCell1 = row1.createCell(1);
        headerCell1.setCellValue("訂單確認率");
        headerCell1.setCellStyle(style.get("header"));
        HSSFCell headerCell2 = row1.createCell(2);
        headerCell2.setCellValue("PO成功率");
        headerCell2.setCellStyle(style.get("header"));
        HSSFCell headerCell3 = row1.createCell(3);
        headerCell3.setCellValue("MO成功率");
        headerCell3.setCellStyle(style.get("header"));
        HSSFCell headerCell4 = row1.createCell(4);
        headerCell4.setCellValue("MR成功率");
        headerCell4.setCellStyle(style.get("header"));
        HSSFCell headerCell5 = row1.createCell(5);
        headerCell5.setCellValue("計費轉化率");
        headerCell5.setCellStyle(style.get("header"));
        for(int i=2; i<100; i++){
            HSSFRow tempRow = sheet.createRow(i);
            tempRow.setHeightInPoints(22);
            for(int j=0; j<6; j++){
                HSSFCell cellCell = tempRow.createCell(j);
                cellCell.setCellValue(i+"--"+j);
                if(j%2==0){
                    cellCell.setCellStyle(style.get("cell1"));
                }else{
                    cellCell.setCellStyle(style.get("cell2"));
                }
            }
        }
        
        FileOutputStream fops = new FileOutputStream("F://Excel//通道平均信息分析報表.xls");
        workbook.write(fops);
        fops.close();
         
        InputStream inst = new FileInputStream("F://Excel//通道平均信息分析報表.xls");
        BufferedInputStream bis = new BufferedInputStream(inst);
        OutputStream oust = _response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(oust);
         
         
        _response.setContentType("application/vnd.ms-excel");
        _response.setHeader("Content-disposition", "attachment;filename=YourDownloadExcel.xls");
        _response.setCharacterEncoding("utf-8");
         
        int flag = 0;
        byte[] tempBuffer = new byte[5 * 1024];
        while((flag = bis.read(tempBuffer)) != -1){
            bos.write(tempBuffer, 0, flag);
        }
        bis.close();
        bos.close();
        inst.close();
        oust.close();
    }


在同一個類中添加入代碼:app

/**
 * Create a library of cell styles
 */
private static Map<String, CellStyle> createStyles(Workbook wb){
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
        CellStyle style;
        Font titleFont = wb.createFont();
        titleFont.setFontHeightInPoints((short)25);
        titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style = wb.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER); // 設置水平對齊方式
        style.setFillPattern(CellStyle.SOLID_FOREGROUND); //設置填充方式
        style.setFillBackgroundColor(HSSFColor.ORANGE.index); //設置背景顏色
        style.setFillForegroundColor(HSSFColor.TEAL.index); //設置前景顏色
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        style.setFont(titleFont);
        styles.put("title", style);
 
        Font monthFont = wb.createFont();
        monthFont.setFontHeightInPoints((short)20);
        monthFont.setColor(IndexedColors.WHITE.getIndex());
        style = wb.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setFont(monthFont);
        style.setWrapText(true);
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setFillForegroundColor(HSSFColor.GOLD.index);
        styles.put("header", style);
 
        style = wb.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setWrapText(true);
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setFillForegroundColor(HSSFColor.LAVENDER.index);
        styles.put("cell1", style);
        
        style = wb.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setWrapText(true);
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setFillForegroundColor(HSSFColor.ROSE.index);
        styles.put("cell2", style);
 
        style = wb.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setDataFormat(wb.createDataFormat().getFormat("0.00"));
        styles.put("formula", style);
 
        style = wb.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setDataFormat(wb.createDataFormat().getFormat("0.00"));
        styles.put("formula_2", style);
 
        return styles;
    }

導出後的Excel以下圖所示:url

Excel分前景色和後景色,前景色的設置須要調用以下方法:spa

void org.apache.poi.ss.usermodel.CellStyle.setFillForegroundColor(short bg)

,背景色的設置須要調用方法是:excel

void org.apache.poi.ss.usermodel.CellStyle.setFillBackgroundColor(short bg)

填充參數bg的一個簡單例子----HSSFColor.ORANGE.index。HSSFColor索引對照表見博客最下方的對照表。code

設置填充模式使用orm

void org.apache.poi.ss.usermodel.CellStyle.setFillPattern(short fp)

填充參數fp的一個簡單例子-----CellStyle.SOLID_FOREGROUND。CellStyle索引對照表見下方圖片:


HSSFColor索引對照表:

.            

HSSFColor.GREY_80_PERCENT

.

HSSFColor.INDIGO

.

HSSFColor.PLUM


HSSFColor.BROWN

.

HSSFColor.OLIVE_GREEN

.

HSSFColor.DARK_GREEN

.

HSSFColor.SEA_GREEN

.

HSSFColor.DARK_TEAL

.

HSSFColor.GREY_40_PERCENT

.

HSSFColor.BLUE_GREY

.

HSSFColor.ORANGE

.

HSSFColor.LIGHT_ORANGE

.

HSSFColor.GOLD

.

HSSFColor.LIME

.

HSSFColor.AQUA

.

HSSFColor.LIGHT_BLUE

.

HSSFColor.TAN

.

HSSFColor.LAVENDER

.

HSSFColor.ROSE

.

HSSFColor.PALE_BLUE

.

HSSFColor.LIGHT_YELLOW

.

HSSFColor.LIGHT_GREEN

.

HSSFColor.LIGHT_TURQUOISE

.

HSSFColor.SKY_BLUE

.

HSSFColor.BLUE

.

HSSFColor.TEAL

.

HSSFColor.DARK_RED

.

HSSFColor.VIOLET

.

HSSFColor.TURQUOISE

.

HSSFColor.YELLOW

.

HSSFColor.PINK

.

HSSFColor.DARK_BLUE

.

HSSFColor.LIGHT_CORNFLOWER_BLUE

.

HSSFColor.ROYAL_BLUE

.

HSSFColor.CORAL

.

HSSFColor.ORCHID

.

HSSFColor.LIGHT_TURQUOISE

.

HSSFColor.LEMON_CHIFFON

.

HSSFColor.PLUM

.

HSSFColor.CORNFLOWER_BLUE

.

HSSFColor.GREY_50_PERCENT

.

HSSFColor.GREY_25_PERCENT

.

HSSFColor.TEAL

.

HSSFColor.VIOLET

.

HSSFColor.DARK_YELLOW

.

HSSFColor.DARK_BLUE

.

HSSFColor.GREEN

.

HSSFColor.DARK_RED

.

HSSFColor.TURQUOISE

.

HSSFColor.PINK

.

HSSFColor.YELLOW

.

HSSFColor.BLUE

.

HSSFColor.BRIGHT_GREEN

.

HSSFColor.RED

.

HSSFColor.WHITE

.

HSSFColor.BLACK

相關文章
相關標籤/搜索