package com.sinosoft.em.baobiao.rcbb.dao; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.ProduceMime; import org.apache.log4j.Logger; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDateUtil; 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.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.formaction.Parameter; import com.formaction.Utils; import com.formaction.vo.Msg; import com.persistence.DbConnection; import com.persistence.service.PersistenceFactory; import com.persistence.service.SysPersistence; import com.persistence.service.assitant.generator.IdentityGenerator; import com.persistence.service.exception.PersistenceException; import com.sinosoft.common.excel.JsonPluginsUtil; import com.sinosoft.em.baobiao.xianlutingyun.vo.XianlutingyunBean; import com.sinosoft.lz.system.util.JsonUtil; import com.sysmodel.datamodel.xmlmodel.ModelFactory; import com.sysmodel.datamodel.xmlmodel.able.MdpClass; import com.sysmodel.datamodel.xmlmodel.able.SysModel; import com.sysmodel.datamodel.xmlmodel.impl.MdpAttributeImpl; /** * 读取Excel将数据返回到頁面 * * @author 彭志超 * */ public class XianluTingyunExcel { // private String columns_info =""; // private String report_type; private static final Logger log = Logger.getLogger(XianluTingyunExcel.class); public String readExcelByName(String fileName,String report_type) { // this.report_type=report_type; XianluTingyunExcel tool = new XianluTingyunExcel(); // String fileName=Utils.getParameter("fileName", params) == null ? "" : Utils.getParameter( // "fileName", params); //// // BaoBiaoDao bbd=new BaoBiaoDao(); // String columns_info=bbd.getTabCol(report_type); // String fileName="E:\\javaDemo\\person.xls"; int i=fileName.lastIndexOf("."); String type=fileName.substring(i+1); log.info("fileName===="+fileName); String result=""; if("xls".equals(type)){ result=tool.readExcel(fileName,report_type); }else if("xlsx".equals(type)){ try { result= tool.readExcel2007(fileName,report_type); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } result="{\"rows\":"+result+"}"; log.info(result); return result; } // public void readExcel2007(DBModel dbConn, String filePath, String tableName) @SuppressWarnings({ "rawtypes", "unused", "resource", "unchecked" }) public String readExcel2007( String filePath, String report_type) { String result=""; try { // InputStream inp = new FileInputStream(filePath); // Workbook wb = WorkbookFactory.create(inp); XSSFWorkbook wb = new XSSFWorkbook(filePath); int sheetSize = wb.getNumberOfSheets(); // for (int i = 0; i < sheetSize; i++) { List list=new ArrayList(); XSSFSheet sheet = wb.getSheetAt(0); // Sheet sheet = wb.getSheetAt(i); int lastRow = sheet.getLastRowNum(); for (int i=1;i<=lastRow;i++) { // 迭代行 // XSSFRow row = (XSSFRow) rit.next(); XSSFRow row = sheet.getRow(i); // 迭代单元格 Vector datas = new Vector(); StringBuffer sb=new StringBuffer(); MaplineMap=new HashMap(); for (Iterator cit = row.cellIterator(); cit.hasNext();) { // 定义集合datas用于存Excel中一个行的数据 XSSFCell cell = (XSSFCell) cit.next(); String value = getValue2007(cell); sb.append(value+"|"); // 注意行和列是基于0索引的 // System.out.print(cell.getRowIndex() + ":" + cell.getColumnIndex() + " "); datas.add(value); // System.out.println(); // 开始操作单元格 } String[] arr=sb.toString().split("[|]"); list.add(arr); // result = fillMap(list);; // 向表中插入数据 // DBFactory.insertData(dbConn, tableName, datas); } result = fillMap(list,report_type); System.out.println(result); // } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // result = new String(result.getBytes("iso8859-1"),"UTF-8"); return result; } /** * 根据ID获取单位名称 * @param id * @return */ public String getNameById(String id){ SysModel sysmodel = ModelFactory.getSysmodel(); SysPersistence persistence = PersistenceFactory.getInstance(sysmodel); String sql="select dept_name from sys_department where id='"+id+"'"; try { ListtempList= persistence.getSearchResult(99, sql.toString()); if(tempList==null||tempList.size()==0){ return ""; }else{ String name=tempList.get(0)[0]; log.info("name===="+name); return name; } } catch (PersistenceException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } } /** * 將数据转换成json * @param list * @return * @throws UnsupportedEncodingException */ public String fillMap(List list,String report_type) throws UnsupportedEncodingException{ RcBbDao bbd=new RcBbDao(); String columns_info=bbd.getTabCol(report_type); String columns=columns_info.split("[|]")[0]; // String tabName=columns_info.split("[|]")[0]; String []col_arr=columns.split(","); List>dataList=new ArrayList>(); Map noHuizongMap = getNoHuizongCol(report_type); MaphuiZongMap=new HashMap(); MaphMap=new HashMap(); for(int i=0;itempMap=new HashMap(); String[]arr=list.get(i); tempMap.put("COMP_ID", getIdByName(arr[0])); tempMap.put("COMP_NAME", new String(java.net.URLEncoder.encode(arr[0], "utf-8").getBytes(),"ISO-8859-1")); tempMap.put("FD_OBJECTID", IdentityGenerator.getIdentityGenerator().gerenalIdentity(338)); for(int j=0;j getNoHuizongCol(String report_type) { SysModel sysmodel = ModelFactory.getSysmodel(); SysPersistence persistence = PersistenceFactory.getInstance(sysmodel); Map map = new HashMap(); String sql = "select TABLE_COLUMN from EMC_AM_REPORT_DICTIONARY where is_del='0' and (is_count='1' or is_count='2') and is_used='0' and report_type='" + report_type + "'"; try { List tempList = persistence.getSearchResult(99, sql.toString()); if (tempList != null && tempList.size() > 0) { for (int i = 0; i < tempList.size(); i++) { map.put(tempList.get(i)[0], tempList.get(i)[0]); } } } catch (PersistenceException e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; } public String getIdByName(String name){ SysModel sysmodel = ModelFactory.getSysmodel(); SysPersistence persistence = PersistenceFactory.getInstance(sysmodel); String result=""; String sql="select comp_id from REPORT_COMP_DICTIONARY where comp_name='"+name+"'"; try { ListtempList= persistence.getSearchResult(99, sql.toString()); if(tempList==null||tempList.size()==0){ }else{ result=tempList.get(0)[0]; log.info("comp_id===="+result); } } catch (PersistenceException e) { // TODO Auto-generated catch block e.printStackTrace(); return result; } return result; } /** * 将Excel数据导入到表中 * * @param filePath * Excel路径 * @param tableName * 表名 */ // public void readExcel(DBModel dbConn, String filePath, String tableName) @SuppressWarnings({ "unchecked", "rawtypes", "deprecation", "resource" }) public String readExcel( String filePath, String report_type){ String result=""; try { POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream( filePath)); // 创建工作簿 HSSFWorkbook workBook = new HSSFWorkbook(fs); log.info(workBook.getNumberOfSheets()); // System.out.println("工作表个数 :" + workBook.getNumberOfSheets()); for (int i = 0; i < workBook.getNumberOfSheets(); i++) { // 创建工作表 HSSFSheet sheet = workBook.getSheetAt(i); int rows = sheet.getPhysicalNumberOfRows(); // 获得行数 int startRow=0; if("7".equals(report_type)){ startRow=1; }else{ startRow=2; } if (rows > 1) { sheet.getMargin(HSSFSheet.TopMargin); List list=new ArrayList(); for (int r = 1; r < rows; r++) { // 行循环 HSSFRow row = sheet.getRow(r); // if (row != null && r != startRow && r != startRow+1) {// 不取第一行、第二行 if (row != null && r >startRow) {// 不取第一行、第二行 int cells = row.getLastCellNum();// 获得列数 // 定义集合datas用于存Excel中一个行的数据 Vector datas = new Vector(); String[]arr=new String[cells]; ListparamList=new ArrayList(); for (short c = 0; c < cells; c++) { // 列循环 HSSFCell cell = row.getCell(c); if (cell != null) { String value = getValue(cell); // System.out.println("第" + r + "行 " + "第" + c + "列:" + value); datas.add(value); paramList.add(value); arr[c]=value; } } list.add(arr); result = fillMap(list,report_type); // dataIntoDb(tableName, paramList); // 向表中插入数据 // DBFactory.insertData(dbConn, tableName, datas); } } } else { } } } catch (Exception ex) { ex.printStackTrace(); log.info(ex); return ""; //throw ex; } // result = new String(result.getBytes("iso8859-1"),"UTF-8"); return result; } public String getValue2007(XSSFCell cell) { String value = ""; switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: // System.out.println(cell.getRichStringCellValue().getString()); value=cell.getRichStringCellValue().getString(); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { // System.out.println(cell.getDateCellValue()); java.util.Date date = cell.getDateCellValue(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); value = format.format(date); } else { // System.out.println(cell.getNumericCellValue()); value = String.valueOf((cell.getNumericCellValue()+"").split("[.]")[0]); } break; case Cell.CELL_TYPE_BOOLEAN: // System.out.println(cell.getBooleanCellValue()); value = " " + cell.getBooleanCellValue(); break; case Cell.CELL_TYPE_FORMULA: // System.out.println(cell.getCellFormula()); value = cell.getCellFormula(); break; default: System.out.println(); } log.info(value); return value; } /** * 获取Excel中某个单元格的值 * * @param cell * @return * @throws ParseException */ @SuppressWarnings("deprecation") public String getValue(HSSFCell cell) { String value = ""; switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_NUMERIC: // 数值型 System.out.println("数字类型"); if (HSSFDateUtil.isCellDateFormatted(cell)) { // 如果是date类型则 ,获取该cell的date值 value = HSSFDateUtil.getJavaDate(cell.getNumericCellValue()) .toString(); java.util.Date date1 = new Date(value); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); value = format.format(date1); } else {// 纯数字 value = String.valueOf(cell.getNumericCellValue()); if(value!=null||!"".equals(value)){ log.info("value==="+value); value=value.endsWith(".0")?(value.split("[.]")[0]):value; } } break; /* 此行表示单元格的内容为string类型 */ case HSSFCell.CELL_TYPE_STRING: // 字符串型 value = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_FORMULA:// 公式型 // 读公式计算值 value = String.valueOf(cell.getNumericCellValue()); if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串 value = cell.getStringCellValue().toString(); } cell.getCellFormula(); break; case HSSFCell.CELL_TYPE_BOOLEAN:// 布尔 value = " " + cell.getBooleanCellValue(); break; /* 此行表示该单元格值为空 */ case HSSFCell.CELL_TYPE_BLANK: // 空值 value = ""; break; case HSSFCell.CELL_TYPE_ERROR: // 故障 value = ""; break; default: value = cell.getStringCellValue().toString(); } return value; } // public boolean dataIntoDb(String tabName,Listlist) throws ClassNotFoundException, SQLException{ // Class.forName("dm.jdbc.driver.DmDriver"); // Connection conn = DriverManager.getConnection("jdbc:dm://192.168.1.16:5236","NWYJ","NWYJ123456"); // String sql="INSERT INTO SYS_MSG_MODEL(FD_OBJECTID,MSG_MODEL_TYPE,MSG_MODEL_CONTENT,MSG_MODEL_RANGE,MSG_MODEL_COMP,MSG_MODEL_USER,MSG_MODEL_TIME,IS_DEL)VALUES(?,?,?,?,?,?,?,?)"; // PreparedStatement ps=null; // conn.setAutoCommit(false); // ps = conn.prepareStatement(sql); // ps.setString(1, (long) ((Math.random()+1)*1000000000)+""); // ps.setString(2, list.get(0)); // ps.setString(3,list.get(1)); // ps.setString(4, list.get(2)); // ps.setString(5, list.get(3)); // ps.setString(6, list.get(4)); // ps.setString(7, list.get(5)); // ps.setString(8,list.get(6)); // int k=ps.executeUpdate(); // conn.commit(); //// System.out.println("k====="+k); // return false; // } public Msg xianluToDb(String fd_id,String json,String report_id,String classId) throws ClassNotFoundException { Msg m=new Msg(); Connection conn = null; PreparedStatement st = null; DbConnection db = new DbConnection(); RcBbDao bbd=new RcBbDao(); // String columns_info=bbd.getTabCol(report_type); // String tabName=columns_info.split("[|]")[1]; // String columns=columns_info.split("[|]")[0]; // String[]arr=columns.split(","); SysModel sysmodel = ModelFactory.getSysmodel(); MdpClass mdpClass = sysmodel.getMdpClassByClassID(Integer.parseInt(classId)); List attribute = mdpClass.getAllMdpAttributes(); String queryField = ""; String tableName = mdpClass.getName(); Map expMap = new HashMap(); for(MdpAttributeImpl attr : attribute){ if(!"UPDATEDATE".equals(attr.getName()) && !"IS_DEL".equals(attr.getName())&& !"USER_LIMITS".equals(attr.getName())&&!"FD_OBJECTID".equals(attr.getName())){ queryField += attr.getName() + ","; } } String[] colArr=queryField.split(","); int colNum=colArr.length; StringBuffer sb=new StringBuffer(); StringBuffer sb1=new StringBuffer(); for(int i=0;i -1) { sb1.deleteCharAt(sb1.lastIndexOf(",")); } if (sb.lastIndexOf(",") > -1) { sb.deleteCharAt(sb.lastIndexOf(",")); } List> list = JsonPluginsUtil.jsonToMapList(json); String sql="INSERT INTO "+tableName+" (FD_OBJECTID,COMP_ID,"+sb1.toString()+ // "TRIP_OUT_ONE,NO_RECOVER_ONE," // + "TRIP_OUT_TOTAL_ONE,REMARK_ONE,TRIP_OUT_TWO,NO_RECOVER_TWO,TRIP_OUT_TOTAL_TWO,REMARK_TWO,TRIP_OUT_THREE,NO_RECOVER_THREE,TRIP_OUT_TOTAL_THREE,REMARK_THREE,TRIP_OUT_FOUR,NO_RECOVER_FOUR,TRIP_OUT_FIVE,NO_RECOVER_FIVE,LOSS_LOAD,LOSS_PERCENT," ",REPORT_ID) VALUES("+sb.toString() // + "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?" + ")"; try { conn = db.getConnection(); int num=0; conn.setAutoCommit(false); st = conn.prepareStatement(sql); for(int i=0;imap=list.get(i); String fd_objectid=map.get("FD_OBJECTID"); st.setString(1, fd_objectid); st.setString(2, map.get("COMP_ID")); for(int k=0;k getMsgId() throws ClassNotFoundException { String sql = "SELECT FD_OBJECTID FROM ROUTE_OFLINE_RESTORE"; Connection conn = null; Statement stat = null; ResultSet rs = null; DbConnection db = new DbConnection(); try { conn = db.getConnection(); stat = conn.createStatement(); rs = stat.executeQuery(sql); List list = new ArrayList(); while (rs.next()) { list.add(rs.getString("FD_OBJECTID")); } return list; } catch (SQLException e) { // this.log.error(e.getMessage(), e); throw new ClassNotFoundException("DAO Layou: 获得数据库消息ID集合" + sql, e); } finally { db.close(rs); db.close(stat); db.close(conn); } } public String createMsgId(List list) throws ClassNotFoundException{ long l=(long) ((Math.random()+1)*1000000000); String msgId=l+""; if(list.contains(msgId)){ return createMsgId(list); } else{ // log.info("msgid==="+msgId); return msgId; } } }