package com.yd.common; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateFormatUtils; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CreationHelper; 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.usermodel.WorkbookFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Excel,Map 操作类 * @author zwc */ public class ExcelUtil { private static String FILE_URL="WebRoot/WEB-INF/svn/nodeInfo.xls"; // private static String FILE_URL="D:/java/server/apache-tomcat-6.0.29/webapps/aether/WEB-INF/svn/anone/nodeInfo.xls"; private static final Logger logger = LoggerFactory .getLogger(ExcelUtil.class); private static String BLANK_NULL = ""; //限定对null和空值的处理 public static String KEY_PREFIX = "attribute"; private static String XLS_FILENAME = "nodeInfo.xls"; /** * 读取Excel表格内容到List<br> * <font color=red>参数说明:</font><br> * 查找参数中,key是Excel的索引,值为,要匹配的内容【仅支持相等比较,不支持大小,相似比较】<br> * <font color=red>Excel要求:</font><br> * 0.Excel的,版本是2003或者2007,其中2007待测试<br> * 1.Excel的数据读取,从第二行开始,第一行,为标题内容<br> * 2.可以对Excel表格中的,各个Sheet进行读取,每个Sheet,必须符合要求1<br> * 3.默认一条记录的,第一个单元格,为主键值,不能为空,如果为空,则不读取该记录,可利用此要求,在Excel后面追加说明文字 * @param params 查找条件Map,key是Excel的索引,值为,要匹配的内容 * @return */ public static List<Map<String,Object>> excel2List(Map<String,Object> params,HttpServletRequest request){ List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); String fileFullPath = null; if(request != null){ String path = request.getSession().getServletContext().getRealPath("WEB-INF/svn/"); String userPath = (String)params.get("username"); fileFullPath = path + File.separator + userPath + File.separator + XLS_FILENAME; }else fileFullPath = FILE_URL; Iterator<String> it = params.keySet().iterator(); while(it.hasNext()){ String key = it.next(); System.out.println(key + ":" + params.get(key)); } System.out.println("fileFullPath=" + fileFullPath); if(isExist(fileFullPath)){ try { //Workbook wb = WorkbookFactory.create(new FileInputStream("D:/java/server/apache-tomcat-6.0.29/webapps/aether/WEB-INF/svn/nodeInfo.xls")); Workbook wb = WorkbookFactory.create(new FileInputStream(fileFullPath)); int sheetSize = wb.getNumberOfSheets(); logger.info("总共的sheet的数量:" + sheetSize); int fieldSize = 0; //总共的字段数量[通过查找第一sheet表得到,以后的sheet以第一个表为准] for(int i = 0; i < sheetSize ; i++){ Sheet sheet = wb.getSheetAt(i); //得到首行所显示的字段 if(i == 0){ Row row = sheet.getRow(0); Map<String,Object> fields = new TreeMap<String,Object>(new MyComparator()); Iterator<Cell> iterator = row.cellIterator(); while(iterator.hasNext()){ Cell cell = iterator.next(); fields.put(KEY_PREFIX + cell.getColumnIndex(), cell.getStringCellValue()); } fieldSize = fields.size(); logger.info("Excel对应的字段数量:" + fieldSize); //list.add(0, fields); } //得到记录,从第二行开始 int lastRowNum = sheet.getLastRowNum(); for(int j = 1;j <= lastRowNum; j++){ Row row = sheet.getRow(j); //主键不能为空,判断区 if(row.getCell(0) == null){ continue; } Map<String,Object> results = new TreeMap<String,Object>(new MyComparator()); for(int k = 0; k < fieldSize; k++){ Cell cell = row.getCell(k); if(cell == null){ results.put(KEY_PREFIX + k, BLANK_NULL); }else{ int type = cell.getCellType(); if(type == Cell.CELL_TYPE_STRING){ if(StringUtils.isNotEmpty(cell.getStringCellValue())){ results.put(KEY_PREFIX + k, cell.getStringCellValue()); }else{ results.put(KEY_PREFIX + k, BLANK_NULL); } }else if(type == Cell.CELL_TYPE_NUMERIC){ if(HSSFDateUtil.isCellDateFormatted(cell)){ String ss = DateFormatUtils.format(cell.getDateCellValue(), "yyyy-MM-dd"); results.put(KEY_PREFIX + k,ss); }else{ results.put(KEY_PREFIX + k,cell.getNumericCellValue()); } }else{ results.put(KEY_PREFIX + k,BLANK_NULL); } } } if(isCondition(params,results)){ list.add(results); } } } } catch (Exception e) { logger.warn("读取Excel文档失败",e); } }else{ logger.warn("更新资产svn失败,且资产文档不存在!!"); } logger.info("总共返回的记录数:" + list.size()); return list; } /** * 判断参数,param中的map,条件和结果result,的map中,对应的项目,是否满足 */ private static boolean isCondition(Map<String,Object> params, Map<String,Object> results){ //参数处理 if(params == null || params.size() <= 0){ return true; } Iterator<String> paramKeys = params.keySet().iterator(); while(paramKeys.hasNext()){ String paramKey = paramKeys.next(); if(paramKey.indexOf(KEY_PREFIX) == -1)continue; if(!params.get(paramKey).equals(results.get(paramKey))){ return false; } } return true; } /** * 写List,到Excel表格<br> * <font color=red>注意:<br> * 1.如果你的Excel中,有一个同名的Sheet,那么之前的Sheet会被删除!!<br> * 2.如果参数File为一个目录的File,那么会自动生成自动生成Excel文件:temp + 年月日 + .xls,覆盖同名文件 * </font> * @param results 结果集 * @param file 导出的文件,可以是目录,如果是目录,则自动生成Excel文件:temp + 年月日 + .xls * @param sheetName Excel表格中的,sheet的名称,如果不给,默认为sheet+ 年月日 */ public static void list2Excel(List<Map<String,Object>> results,File file,String sheetName){ if(file.isDirectory()){ String fileName = "temp" + DateFormatUtils.format(new Date(), "yyyy-MM-dd") + ".xls"; file = new File(file.getAbsoluteFile() + File.separator + fileName); file.setWritable(true); logger.info("参数File为一个目录,自动生成一个文件:" + file.getAbsolutePath()); } if(!file.exists()){ file = new File(file.getAbsolutePath()); try { file.createNewFile(); } catch (IOException e) { logger.warn("创建文件失败" + e); return ; } } if(!file.canWrite()){ logger.info("文件没有写入的权限" + file.getAbsolutePath()); return ; } try { Workbook wb = new HSSFWorkbook(); if(sheetName == null || StringUtils.isEmpty(sheetName)){ sheetName = "sheet" + DateFormatUtils.format(new Date(), "yyyy-MM-dd"); } if(wb.getNameIndex(sheetName) != -1){ wb.removeName(sheetName); } Sheet sheet = wb.createSheet(sheetName); sheet.setSelected(true); int rowSize = results.size(); for(int i = 0; i < rowSize ; i++){ Row row = sheet.createRow(i); Map<String,Object> result = results.get(i); Iterator<String> keys = result.keySet().iterator(); int index = 0; while(keys.hasNext()){ Cell cell = row.createCell(index ++, Cell.CELL_TYPE_STRING); cell.setCellValue(String.valueOf(result.get(keys.next()))); } } wb.write(new FileOutputStream(file)); logger.info("导出Excel成功" + file.getAbsolutePath()); } catch (Exception e) { logger.warn("输出Excel表格失败",e); } } /** * 写List,到Excel表格 */ public static void list2Excel(List<Map<String,Object>> results,String filePath,String sheetName){ list2Excel(results, new File(filePath),sheetName); } /** * 判断资产文件是否存在,如果不存在则从svn上更新 */ private static boolean isExist(String fileFullPath){ File f = new File(fileFullPath); if(f.exists()){ return true; }else{ //添加svn更新命令 logger.warn("资产文档不存在,路径:" + fileFullPath); if(updateSVN()){ logger.info("从服务器上更新资产文档"); return true; }else{ logger.warn("资产svn没有更新,文档不存在"); return false; } } } /** * 从svn上更新资产文档 */ private static boolean updateSVN(){ return true; } /** * 格式化输出内容[为了美观] */ public static void formatPrint(List<Map<String,Object>> list){ System.out.println(); for(int i = 0; i < list.size(); i++ ){ Map<String,Object> fields = list.get(i); Iterator<String> keys = fields.keySet().iterator(); while(keys.hasNext()){ System.out.printf("%-15s",fields.get(keys.next())); } System.out.println(); } } public static void main(String[] args) { ExcelUtil excel = new ExcelUtil(); Map<String,Object> params = new TreeMap<String,Object>(); // params.put(KEY_PREFIX + 0, "0003"); // params.put(KEY_PREFIX + 2, "传真机"); List<Map<String,Object>> list = excel.excel2List(params,null); excel.formatPrint(list); excel.list2Excel(list, "C:\\temp",null); } } /** * 实现键值比较[方便以后扩展]<br> * 如果是字符串类型,则匹配是否有前缀 */ final class MyComparator implements Comparator<Object>{ @Override public int compare(Object o1, Object o2) { if(!(o1 instanceof String) || !(o2 instanceof String)){ return ((Comparable)o1).compareTo(o2); } String s1 = String.valueOf(o1); String s2 = String .valueOf(o2); if(s1.indexOf(ExcelUtil.KEY_PREFIX) != -1 && s2.indexOf(ExcelUtil.KEY_PREFIX) != -1){ int a = Integer.valueOf(s1.split(ExcelUtil.KEY_PREFIX)[1]); int b = Integer.valueOf(s2.split(ExcelUtil.KEY_PREFIX)[1]); return Integer.compare(a, b); }else{ return s1.compareTo(s2); } } }