1. 程式人生 > >POI實現匯出Excel級聯操作

POI實現匯出Excel級聯操作

百度經驗關於Eecel怎麼設定級聯下拉的設定
http://jingyan.baidu.com/article/afd8f4de98dad134e286e9a9.html
package com.test;

import java.io.FileOutputStream;
import java.util.HashMap;

import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
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.DataValidation;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Name;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddressList;

public class POICascadeTest {
	
	 private static String EXCEL_HIDE_SHEET_NAME = "excelhidesheetname";   
	    private static String HIDE_SHEET_NAME_SEX = "sexList";     
	    private static String HIDE_SHEET_NAME_PROVINCE = "provinceList";    
	  
	    private HashMap map = new HashMap();  
	    //設定下拉列表的內容     
	    private static String[] sexList = {"男","女"};     
	    private static String[] provinceList = {"浙江","山東","江西","江蘇","四川"};       
	    private static String[] zjProvinceList = {"浙江","杭州","寧波","溫州"};     
	    private static String[] sdProvinceList = {"山東","濟南","青島","煙臺"};     
	    private static String[] jxProvinceList = {"江西","南昌","新餘","鷹潭","撫州"};     
	    private static String[] jsProvinceList = {"江蘇","南京","蘇州","無錫"};    
	    private static String[] scProvinceList = {"四川","成都","綿陽","自貢"};   
	      
	    public static void main(String[] args) {  
	        //使用事例  
	        Workbook wb = new HSSFWorkbook();  
	        
	        // 建立標題欄
	        createExcelMo(wb);  
	        
	        //建立隱藏的Sheet頁
	        creatExcelHidePage(wb);     
	        
	        //資料驗證
	        setDataValidation(wb);   
	        
	        
	        FileOutputStream fileOut;  
	        try {  
	            fileOut = new FileOutputStream("f://excel_template.xls");  
	            wb.write(fileOut);     
	            fileOut.close();  
	        } catch (Exception e) {   
	            e.printStackTrace();  
	        }     
	    }  
	    public static void  createExcelMo(Workbook wb){  
	            Sheet sheet = wb.createSheet("使用者分類新增批導");     
	            // Create a row and put some cells in it. Rows are 0 based.     
	            Row row = sheet.createRow(0);     
	            Cell cell = row.createCell(0);     
	            cell.setCellValue("手機號碼");     
	            cell.setCellStyle(getTitleStyle(wb));     
	            cell = row.createCell(1);     
	            cell.setCellValue("所屬父類");     
	            cell.setCellStyle(getTitleStyle(wb));     
	            cell = row.createCell(2);     
	            cell.setCellValue("所屬子類");     
	            cell.setCellStyle(getTitleStyle(wb));     
	            cell = row.createCell(3);     
	    }   
	    /**   
	     * 設定模板檔案的橫向表頭單元格的樣式   
	     * @param wb   
	     * @return   
	     */    
	    private static CellStyle getTitleStyle(Workbook wb){     
	        CellStyle style = wb.createCellStyle();     
	        //對齊方式設定     
	        style.setAlignment(CellStyle.ALIGN_CENTER);     
	        //邊框顏色和寬度設定     
	        style.setBorderBottom(CellStyle.BORDER_THIN);     
	        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());     
	        style.setBorderLeft(CellStyle.BORDER_THIN);     
	        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());     
	        style.setBorderRight(CellStyle.BORDER_THIN);     
	        style.setRightBorderColor(IndexedColors.BLACK.getIndex());     
	        style.setBorderTop(CellStyle.BORDER_THIN);     
	        style.setTopBorderColor(IndexedColors.BLACK.getIndex());     
	        style.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.getIndex());     
	        //設定背景顏色     
	        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());     
	        style.setFillPattern(CellStyle.SOLID_FOREGROUND);     
	        //粗體字設定     
	        Font font = wb.createFont();     
	        font.setBoldweight(Font.BOLDWEIGHT_BOLD);     
	        style.setFont(font);     
	        return style;     
	    }    
	    /**   
	     * 設定模板檔案的橫向表頭單元格的樣式   
	     * @param wb   
	     * @return   
	     */   
	    public static void creatExcelHidePage(Workbook workbook){     
	        Sheet hideInfoSheet = workbook.createSheet(EXCEL_HIDE_SHEET_NAME);//隱藏一些資訊     
	        //在隱藏頁設定選擇資訊     
	        //第一行設定性別資訊     
	        Row sexRow = hideInfoSheet.createRow(0);     
	        creatRow(sexRow, sexList);     
	        //第二行設定省份名稱列表     
	        Row provinceNameRow = hideInfoSheet.createRow(1);     
	        creatRow(provinceNameRow, provinceList);     
	        //以下行設定城市名稱列表     
	        Row cityNameRow = hideInfoSheet.createRow(2);     
	        creatRow(cityNameRow, zjProvinceList);     
	          
	        cityNameRow = hideInfoSheet.createRow(3);     
	        creatRow(cityNameRow, sdProvinceList);     
	             
	        cityNameRow = hideInfoSheet.createRow(4);     
	        creatRow(cityNameRow, jxProvinceList);     
	             
	        cityNameRow = hideInfoSheet.createRow(5);     
	        creatRow(cityNameRow, jsProvinceList);     
	             
	        cityNameRow = hideInfoSheet.createRow(6);     
	        creatRow(cityNameRow, scProvinceList);  
	        //名稱管理     
	        //第一行設定性別資訊     
	        creatExcelNameList(workbook, HIDE_SHEET_NAME_SEX, 1, sexList.length, false);     
	        //第二行設定省份名稱列表     
	        creatExcelNameList(workbook, HIDE_SHEET_NAME_PROVINCE, 2, provinceList.length, false);     
	        //以後動態大小設定省份對應的城市列表     
	        creatExcelNameList(workbook, provinceList[0], 3, zjProvinceList.length, true);     
	        creatExcelNameList(workbook, provinceList[1], 4, sdProvinceList.length, true);     
	        creatExcelNameList(workbook, provinceList[2], 5, jxProvinceList.length, true);     
	        creatExcelNameList(workbook, provinceList[3], 6, jsProvinceList.length, true);     
	        creatExcelNameList(workbook, provinceList[4], 7, scProvinceList.length, true);     
	        //設定隱藏頁標誌     
	        workbook.setSheetHidden(workbook.getSheetIndex(EXCEL_HIDE_SHEET_NAME), true);     
	    }    
	      
	    /**   
	     * 建立一個名稱   
	     * @param workbook   
	     */    
	    private static void creatExcelNameList(Workbook workbook,String nameCode,int order,int size,boolean cascadeFlag){     
	        Name name;     
	        name = workbook.createName();     
	        name.setNameName(nameCode);     
	        name.setRefersToFormula(EXCEL_HIDE_SHEET_NAME+"!"+creatExcelNameList(order,size,cascadeFlag));     
	    }     
	      
	    /**   
	     * 名稱資料行列計算表示式   
	     * @param workbook   
	     */    
	    private static String creatExcelNameList(int order,int size,boolean cascadeFlag){     
	    	 char start = 'A';     
	         if(cascadeFlag){     
	             start = 'B';     
	             if(size<=25){     
	                 char end = (char)(start+size-1);     
	                 return "$"+start+"$"+order+":$"+end+"$"+order;     
	             }else{     
	                 char endPrefix = 'A';     
	                 char endSuffix = 'A';     
	                 if((size-25)/26==0||size==51){//26-51之間,包括邊界(僅兩次字母表計算)     
	                     if((size-25)%26==0){//邊界值     
	                         endSuffix = (char)('A'+25);     
	                     }else{     
	                         endSuffix = (char)('A'+(size-25)%26-1);     
	                     }     
	                 }else{//51以上     
	                     if((size-25)%26==0){     
	                         endSuffix = (char)('A'+25);     
	                         endPrefix = (char)(endPrefix + (size-25)/26 - 1);     
	                     }else{     
	                         endSuffix = (char)('A'+(size-25)%26-1);     
	                         endPrefix = (char)(endPrefix + (size-25)/26);     
	                     }     
	                 }     
	                 return "$"+start+"$"+order+":$"+endPrefix+endSuffix+"$"+order;     
	             }     
	         }else{     
	             if(size<=26){     
	                 char end = (char)(start+size-1);     
	                 return "$"+start+"$"+order+":$"+end+"$"+order;     
	             }else{     
	                 char endPrefix = 'A';     
	                 char endSuffix = 'A';     
	                 if(size%26==0){     
	                     endSuffix = (char)('A'+25);     
	                     if(size>52&&size/26>0){     
	                         endPrefix = (char)(endPrefix + size/26-2);     
	                     }     
	                 }else{     
	                     endSuffix = (char)('A'+size%26-1);     
	                     if(size>52&&size/26>0){     
	                         endPrefix = (char)(endPrefix + size/26-1);     
	                     }     
	                 }     
	                 return "$"+start+"$"+order+":$"+endPrefix+endSuffix+"$"+order;     
	             }     
	         }     
	    }   
	      
	    /**   
	     * 建立一列資料   
	     * @param currentRow   
	     * @param textList   
	     */    
	    private static void creatRow(Row currentRow,String[] textList){     
	        if(textList!=null&&textList.length>0){     
	            int i = 0;     
	            for(String cellValue : textList){     
	                Cell userNameLableCell = currentRow.createCell(i++);     
	                userNameLableCell.setCellValue(cellValue);     
	            }     
	        }     
	    }/**   
	     * 新增資料驗證選項   
	     * @param sheet   
	     */    
	    public static void setDataValidation(Workbook wb){     
	        int sheetIndex = wb.getNumberOfSheets();     
	        if(sheetIndex>0){     
	            for(int i=0;i<sheetIndex;i++){     
	                Sheet sheet = wb.getSheetAt(i);     
	                if(!EXCEL_HIDE_SHEET_NAME.equals(sheet.getSheetName())){  
	                    DataValidation data_validation_list = null;  
	                    //省份選項新增驗證資料      
	                    for(int a=2;a<3002;a++){  
	                        data_validation_list = getDataValidationByFormula(HIDE_SHEET_NAME_PROVINCE,a,2);     
	                        sheet.addValidationData(data_validation_list);     
	                        //城市選項新增驗證資料       
	                        data_validation_list = getDataValidationByFormula("INDIRECT($B"+(a-1)+")",a,3);     
	                        sheet.addValidationData(data_validation_list);     
	                        //性別新增驗證資料       
	                        data_validation_list = getDataValidationByFormula(HIDE_SHEET_NAME_SEX,a,1);     
	                        sheet.addValidationData(data_validation_list);       
	                    }  
	                }     
	            }     
	        }     
	    }    
	    /**   
	     * 使用已定義的資料來源方式設定一個數據驗證   
	     * @param formulaString   
	     * @param naturalRowIndex   
	     * @param naturalColumnIndex   
	     * @return   
	     */    
	    private static DataValidation getDataValidationByFormula(String formulaString,int naturalRowIndex,int naturalColumnIndex){     
	        //載入下拉列表內容       
	        DVConstraint constraint = DVConstraint.createFormulaListConstraint(formulaString);      
	        //設定資料有效性載入在哪個單元格上。       
	        //四個引數分別是:起始行、終止行、起始列、終止列       
	        int firstRow = naturalRowIndex-1;     
	        int lastRow = naturalRowIndex-1;     
	        int firstCol = naturalColumnIndex-1;     
	        int lastCol = naturalColumnIndex-1;     
	        CellRangeAddressList regions=new CellRangeAddressList(firstRow,lastRow,firstCol,lastCol);       
	        //資料有效性物件      
	        DataValidation data_validation_list = new HSSFDataValidation(regions,constraint);     
	        //設定輸入資訊提示資訊     
	        data_validation_list.createPromptBox("下拉選擇提示","請使用下拉方式選擇合適的值!");     
	        //設定輸入錯誤提示資訊     
	        data_validation_list.createErrorBox("選擇錯誤提示","你輸入的值未在備選列表中,請下拉選擇合適的值!");     
	        return data_validation_list;     
	    }     
	      
	    private static DataValidation getDataValidationByDate(int naturalRowIndex,int naturalColumnIndex){     
	        //載入下拉列表內容       
	        DVConstraint constraint = DVConstraint.createDateConstraint(DVConstraint.OperatorType.BETWEEN,"1900-01-01", "5000-01-01", "yyyy-mm-dd");      
	        //設定資料有效性載入在哪個單元格上。       
	        //四個引數分別是:起始行、終止行、起始列、終止列       
	        int firstRow = naturalRowIndex-1;     
	        int lastRow = naturalRowIndex-1;     
	        int firstCol = naturalColumnIndex-1;     
	        int lastCol = naturalColumnIndex-1;     
	        CellRangeAddressList regions=new CellRangeAddressList(firstRow,lastRow,firstCol,lastCol);       
	        //資料有效性物件      
	        DataValidation data_validation_list = new HSSFDataValidation(regions,constraint);     
	        //設定輸入資訊提示資訊     
	        data_validation_list.createPromptBox("日期格式提示","請按照'yyyy-mm-dd'格式輸入日期值!");     
	        //設定輸入錯誤提示資訊     
	        data_validation_list.createErrorBox("日期格式錯誤提示","你輸入的日期格式不符合'yyyy-mm-dd'格式規範,請重新輸入!");     
	        return data_validation_list;     
	    }      
}