1. 程式人生 > >poi匯出下拉列表,進行資料有效性約束

poi匯出下拉列表,進行資料有效性約束

package cn.ccf.police.util;


import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.hssf.util.CellRangeAddressList;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Name;


import cn.ccf.police.common.ExcelConstant;


public class ExcelUtil {

/** 
     * 這是一個通用的方法,利用了JAVA的反射機制,可以將放置在JAVA集合中並且符號一定條件的資料以EXCEL 的形式輸出到指定IO裝置上 
     *  
     * @param title 
     *            表格標題名 
     * @param headers 
     *            表格屬性列名陣列 
     * @param dataset 
     *            需要顯示的資料集合,集合中一定要放置符合javabean風格的類的物件。此方法支援的 
     *            javabean屬性的資料型別有基本資料型別及String,Date,byte[](圖片資料) 
     * @param out 
     *            與輸出裝置關聯的流物件,可以將EXCEL文件匯出到本地檔案或者網路中 
     * @param pattern 
     *            如果有時間資料,設定輸出格式。預設為"yyy-MM-dd" 
     */  
public static HSSFWorkbook exportExcel(String title[],String[] headers,Collection<Object> dataset, String pattern,Map<Integer,String[]> map){
// 宣告一個工作薄  
      /*  HSSFWorkbook workbook = new HSSFWorkbook();  
        // 生成一個表格  
        HSSFSheet sheet = workbook.createSheet(title[0]);  
        HSSFRow row = sheet.createRow((short) 0);
        for(int i=0;i<headers.length;i++){
        HSSFCell cell = row.createCell(i);
        HSSFRichTextString text = new HSSFRichTextString(headers[i]);  
             cell.setCellValue(text); 
        }
        
        HSSFSheet sheet1 = workbook.createSheet(title[1]); 
     int j=0;
     for(Entry<String,String[]> entry:map.entrySet()){
    HSSFRow row1 = sheet1.createRow(j);
    HSSFCell cell = row1.createCell(0);
     row1.createCell(1);
     HSSFRichTextString text = new HSSFRichTextString(entry.getKey());
     cell.setCellValue(text);
     CellRangeAddressList regions = new CellRangeAddressList(j,j,1,1);  
         String[] str=entry.getValue();
         //生成下拉框內容  
         DVConstraint constraint = DVConstraint.createExplicitListConstraint(str);  
        
         //繫結下拉框和作用區域  
         HSSFDataValidation data_validation = new HSSFDataValidation(regions,constraint);   
          
         //對sheet頁生效  
         sheet1.addValidationData(data_validation); 
     }*/
HSSFWorkbook workbook = new HSSFWorkbook(); 
// 生成一個表格  
        HSSFSheet sheet = workbook.createSheet(title[0]);  
        HSSFRow row = sheet.createRow((short) 0);
        for(int i=0;i<headers.length;i++){
        HSSFCell cell = row.createCell(i);
        HSSFRichTextString text = new HSSFRichTextString(headers[i]);  
             cell.setCellValue(text); 
        }
        
       // HSSFSheet realSheet = workbook.createSheet(title[1]);
HSSFSheet hidden = workbook.createSheet("hidden");
//資料來源sheet頁不顯示
workbook.setSheetHidden(1, true);
//String[] datas = dataSource.split("\\,");
CellStyle style = workbook.createCellStyle();
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("0"));
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
int j=0;
int sum=0;
HSSFCell cell = null;
List<String> strList=new ArrayList<String>();
for(Entry<Integer,String[]> entry:map.entrySet()){

String[] list =entry.getValue();

for (int i = 0, length = list.length; i < length; i++) {
row = hidden.createRow(i+sum+1);

cell = row.createCell(entry.getKey());
cell.setCellValue(list[i]);
}
String s="hidden!$"+ExcelConstant.ExcelColumn[entry.getKey()]+"$"+(sum+2)+":$"+ExcelConstant.ExcelColumn[entry.getKey()]+"$"+(list.length+sum+1);
strList.add(s);
/*Name namedCell = workbook.createName();
namedCell.setNameName("hidden"+j);


if(list.length>0){
namedCell.setRefersToFormula(s);
}
String name = namedCell.getNameName();
DVConstraint constraint = DVConstraint
.createFormulaListConstraint(name);
//會造成異常
//DVConstraint constraint = DVConstraint.createExplicitListConstraint(list);
CellRangeAddressList addressList = null;
HSSFDataValidation validation = null;



row = sheet.createRow(1);

cell = row.createCell(entry.getKey());
//cell.setCellValue("請選擇");
cell.setCellStyle(style);
addressList = new CellRangeAddressList(1, 1,entry.getKey(), entry.getKey());
//addressList = new CellRangeAddressList(1+sum, 1+sum,entry.getKey(), entry.getKey());
validation = new HSSFDataValidation(addressList, constraint);
sheet.addValidationData(validation);
validation.setShowErrorBox(true);// 取消彈出錯誤框*/
sum+=entry.getValue().length;
j++;

}

Set<Integer> keySet =map.keySet();
Iterator<Integer> it = keySet.iterator();
int k=0;
CellRangeAddressList addressList = null;
HSSFDataValidation validation = null;
row = sheet.createRow(1);
while(it.hasNext()){
Integer key=it.next();
Name namedCell = workbook.createName();
namedCell.setNameName("hidden"+k);
namedCell.setRefersToFormula(strList.get(k++));
DVConstraint constraint = DVConstraint
.createFormulaListConstraint(namedCell.getNameName());
cell = row.createCell(key);
cell.setCellValue("請選擇");
cell.setCellStyle(style);
addressList = new CellRangeAddressList(1, 1,key, key);
//addressList = new CellRangeAddressList(1+sum, 1+sum,entry.getKey(), entry.getKey());
validation = new HSSFDataValidation(addressList, constraint);
sheet.addValidationData(validation);
validation.setShowErrorBox(true);// 取消彈出錯誤框*/
}


        return workbook;
        
        /*try {
workbook.write(out);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/

}

public static void main(String[] args) throws Exception {

OutputStream out = new FileOutputStream("E://a.xls");
String[] title={"巡組資訊錄入","資料參照"};
String[] str=new String[]{"巡組名稱","地市","分局","派出所","責任單位","巡邏方式","警力配置","工作頻道","分管領導姓名","單位","職務","手機號碼","電話號碼"};
Map<Integer,String[]> m=new LinkedHashMap<Integer,String[]>();

m.put(1, new String[]{"廣州"});
m.put(2, new String[]{"天河"});
m.put(3, new String[]{"棠下","車陂"});
m.put(5, new String[]{"步巡","車巡"});
m.put(9, new String[]{"一單位","二單位"});
m.put(10, new String[]{"局長","所長"});
HSSFWorkbook  workbook = ExcelUtil.exportExcel(title, str, null, null,m);
workbook.write(out);

}


}

---------------------------------------------

package cn.ccf.police.common;


public class ExcelConstant {


public static final String[] ExcelColumn = new String[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};

}

感覺自己萌萌噠.