日期:2014-05-19 浏览次数:20593 次
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class WorkBookPoiUtil { private static List<short[]> widths ; private LinkedHashMap<String, List<?>> map ; private List<LinkedHashMap<String, String>> titles ; /** * * @param map String为菜单名称 ,对应List数据 * @param titles Key为title名称 , value为title属性名称 和 map 对应 title 和 属性 一一对应 */ public WorkBookPoiUtil(LinkedHashMap<String, List<?>> map , List<LinkedHashMap<String, String>> titles ){ this(map, titles, null); } /** * * @param map String为菜单名称 ,对应List数据 * @param titles Key为title名称 , value为title属性名称 和 map 对应 title 和 属性 一一对应 * @param width 设置每一列宽度 * */ public WorkBookPoiUtil(LinkedHashMap<String, List<?>> map , List<LinkedHashMap<String, String>> titles , List<short[]> widths ){ this.widths = widths; this.map = map ; this.titles = titles; } public static void setSheet(LinkedHashMap<String, String> map, List<?> list,HSSFSheet s ,short[] width ) throws Exception{ List<String> strings = new ArrayList<String>(); int i =0 ; for (String key : map.keySet()) { if(width==null || width.length<= i) s.setColumnWidth((short) i,(short)6000); else s.setColumnWidth((short) i, width[i]); s.createRow(0).createCell((short) i).setCellValue(new HSSFRichTextString(key) ); strings.add(map.get(key)); i= i+1 ; } for (int j = 1; j < list.size()+1; j++) { for (int j2 = 0; j2 < strings.size(); j2++) { Class<?> class1 = list.get(j-1).getClass(); String methodName = "get" + strings.get(j2).substring(0, 1).toUpperCase() + strings.get(j2).substring(1); Method method = class1.getMethod(methodName); if ("java.util.Date".equals(method.getReturnType() .getName())) { s.createRow(j).createCell((short) j2).setCellValue(new HSSFRichTextString( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date)method.invoke(list.get(j-1))) )); }else{ s.createRow(j).createCell((short) j2).setCellValue(new HSSFRichTextString(method.invoke(list.get(j-1)).toString())); } } } } /** * * @param pathName 指定路径生成 * @throws Exception */ public void getPathExel(String pathName) throws Exception{ FileOutputStream fos = new FileOutputStream(pathName); HSSFWorkbook wb = new HSSFWorkbook(); int i = 0 ; for (String key : map.keySet()) { HSSFSheet s = wb.createSheet(key); if(widths.size()<=i) setSheet(titles.get(i) , map.get(key) , s , null); else setSheet(titles.get(i) , map.get(key) , s , widths.get(i)); i= i+1; } wb.write(fos); fos.flush(); fos.close(); } /** * * @return ByteArrayInputStream 一个流 * @throws E