poi 操作excel之導出excel

public class ExportExcel  {

    /**
     * 顯示的導出表的標題
     */
    private String title;

    /**
     * 導出表的列名
     */
    private String[] columnName;

    /**
     * 需要導出的數據集合
     */
    private List<Map> dataList = new ArrayList<Map>();

    /**
     * 輸入流對象
     */
    private HttpServletRequest request;

    /**
     * 輸出流對象
     */
    private HttpServletResponse response;


    /**
     *
     * @param title
     * @param columnName
     * @param dataList
     * @param request
     * @param response
     * @description 構造方法,傳入要導出的數據
     */
    public ExportExcel(String title, String[] columnName, List<Map> dataList,HttpServletRequest request,HttpServletResponse response) {
        this.dataList = dataList;
        this.columnName = columnName;
        this.title = title;
        this.request = request;
        this.response= response;
    }


    /**
     * @param
     * @return
     * @description 導出數據到excel
     */
    public void export() throws Exception {

        try {
            HSSFWorkbook workbook = new HSSFWorkbook();                        // 創建工作簿對象
            HSSFSheet sheet = workbook.createSheet(title);                     // 創建工作表
            // 產生表格標題行
            HSSFRow rowm = sheet.createRow(0);
            HSSFCell cellTiltle = rowm.createCell(0);
            //設置標題和單元格樣式
            HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);  //獲取列頭樣式對象
            HSSFCellStyle style = this.getStyle(workbook);                    //單元格樣式對象
            // 定義所需列數
            int columnNum = columnName.length;
            HSSFRow rowRowName = sheet.createRow(0);                 // 在索引2的位置創建行(最頂端的行開始的第二行)
            HSSFRow rowRowName1 = sheet.createRow(1); 

            // 將列頭設置到sheet的單元格中
            for (int n = 0; n < columnNum; n++) {
            	HSSFCell cellRowName;
            	if(n <5){
            		 cellRowName = rowRowName.createCell(n);                  //創建列頭對應個數的單元格
            		 if(n == 4){
            			 cellRowName = rowRowName.createCell(n+6);
            		 }
            	}else{
            		 cellRowName = rowRowName1.createCell(n-2);    
            	}
                if(n < 3){
                	CellRangeAddress region = new CellRangeAddress(0, 1, n, n);
                    sheet.addMergedRegion(region);
                }else if(n == 3){
                	CellRangeAddress region = new CellRangeAddress(0, 0, n, n+6);
                    sheet.addMergedRegion(region);
                }else if(n == 4){
                	CellRangeAddress region = new CellRangeAddress(0, 0, n+6, n+12);
                    sheet.addMergedRegion(region);
                }
                cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);                //設置列頭單元格的數據類型
                HSSFRichTextString text = new HSSFRichTextString(columnName[n]);
                cellRowName.setCellValue(text);                                    //設置列頭單元格的值
                cellRowName.setCellStyle(columnTopStyle);                          //設置列頭單元格樣式
            }

            HSSFRow row;
            //將查詢出的數據設置到sheet對應的單元格中
            for (int i = 0; i < dataList.size(); i++) {
                Map<Object,Object> map = dataList.get(i);//遍歷每個對象
                row = sheet.createRow(i+2);//創建所需的行數
                HSSFCell cell = null;   //設置單元格的數據類型
                int num = 0;
                for (Object value : map.values()) { 
                      cell = row.createCell(num);
                      
                      Boolean isNum = false;//data是否爲數值型
                      Boolean isInteger=false;//data是否爲整數
                      Boolean isPercent=false;//data是否爲百分數
                      if (value != null || "".equals(value)) {
                          //判斷data是否爲數值型
                          isNum = value.toString().matches("^(-?\\d+)(\\.\\d+)?$");
                          //判斷data是否爲整數(小數部分是否爲0)
                          isInteger=value.toString().matches("^[-\\+]?[\\d]*$");
                          //判斷data是否爲百分數(是否包含“%”)
                          isPercent=value.toString().contains("%");
                      }

                      //如果單元格內容是數值類型,涉及到金錢(金額、本、利),則設置cell的類型爲數值型,設置data的類型爲數值類型
                      if (isNum && !isPercent) {
                          HSSFDataFormat df = workbook.createDataFormat(); // 此處設置數據格式
                          if (isInteger) {
                          	style.setDataFormat(df.getBuiltinFormat("#,#0"));//數據格式只顯示整數
                          }else{
                          	style.setDataFormat(df.getBuiltinFormat("#,##0.00"));//保留兩位小數點
                          }                   
                          // 設置單元格內容爲double類型
                          cell.setCellValue(Double.parseDouble(value.toString()));
                      } else {
                          // 設置單元格內容爲字符型
                    	  if(value==null){
                      		value = "";
                      	}
                    	  cell.setCellValue(value.toString());
                      }
                      
                      cell.setCellStyle(style); 
                      num++;
                }
                
            }


            //讓列寬隨着導出的列長自動適應
            for (int colNum = 0; colNum < columnNum; colNum++) {
                int columnWidth = sheet.getColumnWidth(colNum) / 256;
                for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                    HSSFRow currentRow;
                    //當前行未被使用過
                    if (sheet.getRow(rowNum) == null) {
                        currentRow = sheet.createRow(rowNum);
                    } else {
                        currentRow = sheet.getRow(rowNum);
                    }
                    if (currentRow.getCell(colNum) != null) {
                        //取得當前的單元格
                        HSSFCell currentCell = currentRow.getCell(colNum);
                        //如果當前單元格類型爲字符串
                        if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                            int length = currentCell.getStringCellValue().getBytes().length;
                            if (columnWidth < length) {
                                //將單元格里面值大小作爲列寬度
                                columnWidth = length;
                            }
                        }
                    }
                }
                //再根據不同列單獨做下處理
                if (colNum == 0) {
                    sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
                } else {
                    sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);
                }
            }

            
            if (workbook != null) {
            	OutputStream out1 = null;
                try {
                	String fileName =  title+ new SimpleDateFormat("yyyyMMdd").format(new Date()) ;
                    String headStr = "attachment; filename=\""+ new String( fileName.getBytes( "gb2312" ), "ISO8859-1" )+ ".xls" + "\"";
                    response.setContentType("APPLICATION/OCTET-STREAM");
                    response.setHeader("Content-Disposition", headStr);
                    out1 = response.getOutputStream();
                    workbook.write(out1);
                } catch (IOException e) {
                    e.printStackTrace();
                }finally{
                	out1.close();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param
     * @return
     * @description 標題行的單元格樣式
     */
    public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

        // 設置字體
        HSSFFont font = workbook.createFont();
        //設置字體大小
        font.setFontHeightInPoints((short) 11);
        //字體加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //設置字體名字
        font.setFontName("Courier New");
        //設置樣式;
        HSSFCellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
        //設置底邊框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //設置底邊框顏色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //設置左邊框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //設置左邊框顏色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //設置右邊框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //設置右邊框顏色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //設置頂邊框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //設置頂邊框顏色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //在樣式用應用設置的字體;
        style.setFont(font);
        //設置自動換行;
        style.setWrapText(false);
        //設置水平對齊的樣式爲居中對齊;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //設置垂直對齊的樣式爲居中對齊;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        //設置單元格填充色
        style.setFillForegroundColor(IndexedColors.PINK.getIndex());
        return style;
    }

    /**
     * @param
     * @return
     * @description 列數據信息單元格樣式
     */
    public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
        // 設置字體
        HSSFFont font = workbook.createFont();
        //設置字體大小
        //font.setFontHeightInPoints((short)10);
        //字體加粗
        //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //設置字體名字
        font.setFontName("Courier New");
        //設置樣式;
        HSSFCellStyle style = workbook.createCellStyle();
        //設置底邊框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //設置底邊框顏色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //設置左邊框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //設置左邊框顏色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //設置右邊框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //設置右邊框顏色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //設置頂邊框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //設置頂邊框顏色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //在樣式用應用設置的字體;
        style.setFont(font);
        //設置自動換行;
        style.setWrapText(false);
        //設置水平對齊的樣式爲居中對齊;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //設置垂直對齊的樣式爲居中對齊;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        return style;
    }
	
}

 

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