使用apache.poi生成Excel

maven倉庫下載依賴包:

<dependency>
    <groupId>org.apache.poi</groupId>              
    <artifactId>poi</artifactId>
    <version>3.12</version>
</dependency>

傳入Bean生成Excel

/**
     * 導出excel
     * 
     * @param title
     *            sheet名稱
     * @param headers
     *            表格標題行
     * @param dataset
     *            實際數據集
     * @param out
     *            輸出流
     * @param pattern
     *            輸出文件格式
     * @author Bdong
     */
    public void exportExcel(String title, String[] headers,
            Collection<T> dataset, OutputStream out, String pattern) {
        // 聲明一個工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一個表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 設置表格默認列寬度爲15個字節
        sheet.setDefaultColumnWidth(20);
        // 生成一個樣式
        HSSFCellStyle style = workbook.createCellStyle();
        // 設置這些樣式
        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 生成一個字體
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字體應用到當前的樣式
        style.setFont(font);

        // 聲明一個畫圖的頂級管理器
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        // 定義註釋的大小和位置,詳見文檔
        HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
                0, 0, 0, (short) 4, 2, (short) 6, 5));
        // 設置註釋內容
        comment.setString(new HSSFRichTextString("可以在POI中添加註釋!"));
        // 設置註釋作者,當鼠標移動到單元格上是可以在狀態欄中看到該內容.
        comment.setAuthor("Bdong");

        // 產生表格標題行
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 遍歷集合數據,產生數據行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            T t = (T) it.next();
            // 利用反射,根據javabean屬性的先後順序,動態調用getXxx()方法得到屬性值
            Field[] fields = t.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                HSSFCell cell = row.createCell(i);
                Field field = fields[i];
                String fieldName = field.getName();//屬性名
                String getMethodName = "get"//拼接反射需要的方法名
                        + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);
                try {
                    Class tCls = t.getClass();
                    Method getMethod = tCls.getMethod(getMethodName,
                            new Class[] {});
                    Object value = getMethod.invoke(t, new Object[] {});//調用方法獲取屬性值
                    if(value!=null){
                        // 判斷值的類型後進行強制類型轉換
                        HSSFCellStyle cellStyle = workbook.createCellStyle();   
                        if (value instanceof Integer || value instanceof Long) {//整數
                            cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0"));
                            cell.setCellValue(Long.parseLong(value.toString()));
                            cell.setCellStyle(cellStyle);
                        } else if (value instanceof Float || value instanceof Double) {//浮點數
                            cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
                            cell.setCellValue(Double.parseDouble(value.toString()));
                            cell.setCellStyle(cellStyle);
                        } else if (value instanceof Date) {//日期
                            Date date = (Date) value;
                            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                            cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(pattern));
                            cell.setCellValue(sdf.format(date));
                            cell.setCellStyle(cellStyle);
                        } else if (value instanceof byte[]) {//
                            // 有圖片時,設置行高爲60px;
                            row.setHeightInPoints(60);
                            // 設置圖片所在列寬度爲80px,注意這裏單位的一個換算
                            sheet.setColumnWidth(i, (short) (35.7 * 80));
                            byte[] bsValue = (byte[]) value;
                            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
                                    1023, 255, (short) 6, index, (short) 6, index);
                            anchor.setAnchorType(2);
                            patriarch.createPicture(anchor, workbook.addPicture(
                                    bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
                        } else {
                            // 其它數據類型都當作字符串簡單處理
                            cell.setCellValue(value.toString());
                        }
                    }
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    // 清理資源
                }
                // 生成邊框樣式
                HSSFCellStyle style2 = workbook.createCellStyle();
                style2.setFillForegroundColor(HSSFColor.WHITE.index);
                style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
                style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
                style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
                style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
                style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
                // 生成另一個字體
                HSSFFont font2 = workbook.createFont();
                font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
                // 把字體應用到當前的樣式
                style2.setFont(font2);
                cell.setCellStyle(style2);//設置邊框樣式
            }

        }
        try {
            workbook.write(out);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                workbook.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

傳入Map生成Excel

/**
     * @param title
     *            sheet名稱
     * @param headers
     *            表格標題行
     * @param keys Map的key
     * @param dataset
     *            實際數據集
     * @param out
     *            輸出流
     * @param pattern
     *            輸出文件格式
     * @author Bdong
     */
    public void exportExcel(String title, String[] headers,String[] keys,
            List<Map<String,?>> dataset, OutputStream out, String pattern) {
        // 聲明一個工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一個表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 設置表格默認列寬度爲15個字節
        sheet.setDefaultColumnWidth(20);
        // 生成一個樣式
        HSSFCellStyle style = workbook.createCellStyle();
        // 設置這些樣式
        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 生成一個字體
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字體應用到當前的樣式
        style.setFont(font);

        // 聲明一個畫圖的頂級管理器
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        // 定義註釋的大小和位置,詳見文檔
        HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
                0, 0, 0, (short) 4, 2, (short) 6, 5));
        // 設置註釋內容
        comment.setString(new HSSFRichTextString("可以在POI中添加註釋!"));
        // 設置註釋作者,當鼠標移動到單元格上是可以在狀態欄中看到該內容.
        comment.setAuthor("Bdong");

        // 產生表格標題行
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 遍歷List數據,產生數據行
        for(int i=0;i<dataset.size();i++){
            row = sheet.createRow(i+1);
            Map<String,?> map = dataset.get(i);
            for (int j = 0; j < keys.length; j++) {
                HSSFCell cell = row.createCell(j);
                try {
                    Object value = map.get(keys[j]);
                    if(value!=null){
                        // 判斷值的類型後進行強制類型轉換
                        HSSFCellStyle cellStyle = workbook.createCellStyle();   
                        if (value instanceof Integer || value instanceof Long) {//整數
                            cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0"));
                            cell.setCellValue(Long.parseLong(value.toString()));
                            cell.setCellStyle(cellStyle);
                        } else if (value instanceof Float || value instanceof Double) {//浮點數
                            cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
                            cell.setCellValue(Double.parseDouble(value.toString()));
                            cell.setCellStyle(cellStyle);
                        } else if (value instanceof Date) {//日期
                            Date date = (Date) value;
                            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                            cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(pattern));
                            cell.setCellValue(sdf.format(date));
                            cell.setCellStyle(cellStyle);
                        } else if (value instanceof byte[]) {//
                            // 有圖片時,設置行高爲60px;
                            row.setHeightInPoints(60);
                            // 設置圖片所在列寬度爲80px,注意這裏單位的一個換算
                            sheet.setColumnWidth(i, (short) (35.7 * 80));
                            byte[] bsValue = (byte[]) value;
                            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
                                    1023, 255, (short) 6, i, (short) 6, i);
                            anchor.setAnchorType(2);
                            patriarch.createPicture(anchor, workbook.addPicture(
                                    bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
                        } else {
                            // 其它數據類型都當作字符串簡單處理
                            cell.setCellValue(value.toString());
                        }
                    }
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    // 清理資源
                }
                // 生成邊框樣式
                HSSFCellStyle style2 = workbook.createCellStyle();
                style2.setFillForegroundColor(HSSFColor.WHITE.index);
                style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
                style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
                style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
                style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
                style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
                // 生成另一個字體
                HSSFFont font2 = workbook.createFont();
                font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
                // 把字體應用到當前的樣式
                style2.setFont(font2);
                cell.setCellStyle(style2);//設置邊框樣式
            }

        }
        try {
            workbook.write(out);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                workbook.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

使用Bean導出Excel,適用於需要控制Excel的列類型的場景;
使用Map導出Excel,適用於表頭要變化的場景;


調用實例

try {
            ExcelUtil<AdultVideoStar> eu=new ExcelUtil<AdultVideoStar>();//初始化Excel工具
            /**入參準備 start**/
            /**Excel表頭,表頭順序與對象屬性順序一致**/
            String[] headers={ "中文名", "英文名", "出生日期", "身高(cm)", "三圍", "罩杯", "作戰兵種" };
            OutputStream out = new FileOutputStream("/Users/Bdong/Downloads/AdultVideoStar.xls");//Excel存放位置
            Calendar c = Calendar.getInstance();//獲取一個日曆實例  
            Date date =new Date();
            List<AdultVideoStar> AVStarList=new ArrayList<AdultVideoStar>();//Excel實際數據
            ...
            **此處根據實際情況準備List數據**
            /**入參準備 end**/

            /**如果Excel包含日期格式,可按指定格式進行統一格式化,如yyy-MM-dd**/
            eu.exportExcel("AdultVideoStar", headers,AVStarList, out, "yyy-MM-dd");//執行導出
            out.close();//關閉輸出流
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

該工具基於對象的反射實現,所以List所需對象請根據具體情況自行封裝,且表頭順序與對象屬性順序一致
如AdultVideoStar

    private String chineseName;
    private String englishName;
    private Date birthday;
    private int height;
    private String measurements;
    private String cup;
    private String mosaic;

Excel效果展示

這裏寫圖片描述

祝各位工作愉快!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章