0ce6d6f86ada23256bdbbe6663fe48a95c57fee9.svn-base 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. /**
  2. *
  3. */
  4. package com.sinosoft.common.excel;
  5. import java.io.FileInputStream;
  6. import java.io.FileNotFoundException;
  7. import java.io.IOException;
  8. import java.sql.Connection;
  9. import java.sql.PreparedStatement;
  10. import java.sql.ResultSet;
  11. import java.sql.SQLException;
  12. import java.sql.Statement;
  13. import java.text.ParseException;
  14. import java.text.SimpleDateFormat;
  15. import java.util.ArrayList;
  16. import java.util.Date;
  17. import java.util.HashMap;
  18. import java.util.Iterator;
  19. import java.util.List;
  20. import java.util.Map;
  21. import java.util.Vector;
  22. import javax.ws.rs.POST;
  23. import javax.ws.rs.Path;
  24. import javax.ws.rs.ProduceMime;
  25. import org.apache.log4j.Logger;
  26. import org.apache.poi.hssf.usermodel.HSSFCell;
  27. import org.apache.poi.hssf.usermodel.HSSFDateUtil;
  28. import org.apache.poi.hssf.usermodel.HSSFRow;
  29. import org.apache.poi.hssf.usermodel.HSSFSheet;
  30. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  31. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  32. import org.apache.poi.ss.usermodel.Cell;
  33. import org.apache.poi.ss.usermodel.DateUtil;
  34. import org.apache.poi.xssf.usermodel.XSSFCell;
  35. import org.apache.poi.xssf.usermodel.XSSFRow;
  36. import org.apache.poi.xssf.usermodel.XSSFSheet;
  37. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  38. import com.formaction.Parameter;
  39. import com.formaction.Utils;
  40. import com.formaction.vo.Msg;
  41. import com.persistence.DbConnection;
  42. import com.sinosoft.lz.system.util.JsonUtil;
  43. /**
  44. * @author 蒋云涛
  45. *
  46. */
  47. @Path("/UPSGeneratorExcelToDBTableTool/")
  48. public class UPSGeneratorExcelToDBTableTool{
  49. private static final Logger log = Logger.getLogger(GeneratorExcelToDBTableTool.class);
  50. @ProduceMime("application/json")
  51. @POST
  52. @Path("/getUPSGeneratorExcel")
  53. public String readExcelByName(String params) throws Exception {
  54. GeneratorExcelToDBTableTool tool = new GeneratorExcelToDBTableTool();
  55. String fileName=Utils.getParameter("fileName", params) == null ? "" : Utils.getParameter(
  56. "fileName", params);
  57. // String fileName="E:\\javaDemo\\person.xls";
  58. int i=fileName.lastIndexOf(".");
  59. String type=fileName.substring(i+1);
  60. log.info("fileName===="+fileName);
  61. String result="";
  62. if("xls".equals(type)){
  63. result=tool.readExcel(fileName,"person");
  64. }else if("xlsx".equals(type)){
  65. result= tool.readExcel2007(fileName,"person");
  66. }
  67. result="{\"rows\":"+result+"}";
  68. log.info(result);
  69. return result;
  70. }
  71. // public void readExcel2007(DBModel dbConn, String filePath, String tableName)
  72. @SuppressWarnings({ "rawtypes", "unchecked", "unused", "resource" })
  73. public String readExcel2007( String filePath, String tableName)
  74. throws Exception {
  75. String result="";
  76. try {
  77. // InputStream inp = new FileInputStream(filePath);
  78. // Workbook wb = WorkbookFactory.create(inp);
  79. XSSFWorkbook wb = new XSSFWorkbook(filePath);
  80. int sheetSize = wb.getNumberOfSheets();
  81. // for (int i = 0; i < sheetSize; i++) {
  82. List list=new ArrayList();
  83. XSSFSheet sheet = wb.getSheetAt(0);
  84. // Sheet sheet = wb.getSheetAt(i);
  85. for (Iterator rit = sheet.rowIterator(); rit.hasNext();) {
  86. // 迭代行
  87. XSSFRow row = (XSSFRow) rit.next();
  88. // 迭代单元格
  89. Vector datas = new Vector();
  90. StringBuffer sb=new StringBuffer();
  91. Map<String, String>lineMap=new HashMap<String, String>();
  92. for (Iterator cit = row.cellIterator(); cit.hasNext();) {
  93. // 定义集合datas用于存Excel中一个行的数据
  94. XSSFCell cell = (XSSFCell) cit.next();
  95. String value = getValue2007(cell);
  96. sb.append(value+"|");
  97. // 注意行和列是基于0索引的
  98. // System.out.print(cell.getRowIndex() + ":" + cell.getColumnIndex() + " ");
  99. datas.add(value);
  100. // System.out.println();
  101. // 开始操作单元格
  102. }
  103. String[] arr=sb.toString().split("[|]");
  104. list.add(arr);
  105. // result = fillMap(list);;
  106. // 向表中插入数据
  107. // DBFactory.insertData(dbConn, tableName, datas);
  108. }
  109. result = fillMap(list);
  110. System.out.println(result);
  111. // }
  112. } catch (FileNotFoundException e) {
  113. e.printStackTrace();
  114. throw e;
  115. } catch (IOException e) {
  116. e.printStackTrace();
  117. throw e;
  118. }
  119. return result;
  120. }
  121. /**
  122. * 將数据转换成json
  123. * @param list
  124. * @return
  125. */
  126. public String fillMap(List<String[]> list){
  127. List<Map<String, String>>dataList=new ArrayList<Map<String,String>>();
  128. for(int i=0;i<list.size();i++){
  129. Map<String, String>tempMap=new HashMap<String, String>();
  130. String[]arr=list.get(i);
  131. tempMap.put("COMP_267", arr[0]);
  132. tempMap.put("NAME_267", arr[1]);
  133. tempMap.put("MODEL_TYPE_267", arr[2]);
  134. tempMap.put("VOLTAGE_LEVEL_267", arr[3]);
  135. tempMap.put("CONTENT_267", arr[4]);
  136. tempMap.put("NUM_267", arr[5]);
  137. tempMap.put("PRICE_267", arr[6]);
  138. tempMap.put("GAS_267", arr[7]);
  139. tempMap.put("PROVIDER_267", arr[8]);
  140. tempMap.put("BUY_DATE_267", arr[9]);
  141. tempMap.put("STORE_PLACE_267", arr[10]);
  142. tempMap.put("INPIRE_267", arr[11]);
  143. tempMap.put("OFFICE_TEL_267", arr[12]);
  144. tempMap.put("MOBILE_PHONE_267", arr[13]);
  145. tempMap.put("IS_USED_267", arr[14]);
  146. tempMap.put("USED_STAT_267", arr[15]);
  147. dataList.add(tempMap);
  148. }
  149. String result=JsonUtil.list2json(dataList);
  150. return result;
  151. }
  152. /**
  153. * 将Excel数据导入到表中
  154. *
  155. * @param filePath
  156. * Excel路径
  157. * @param tableName
  158. * 表名
  159. */
  160. // public void readExcel(DBModel dbConn, String filePath, String tableName)
  161. @SuppressWarnings({ "unchecked", "rawtypes", "resource", "deprecation" })
  162. public String readExcel( String filePath, String tableName)
  163. throws Exception {
  164. String result="";
  165. try {
  166. POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream( filePath));
  167. // 创建工作簿
  168. HSSFWorkbook workBook = new HSSFWorkbook(fs);
  169. log.info(workBook.getNumberOfSheets());
  170. // System.out.println("工作表个数 :" + workBook.getNumberOfSheets());
  171. for (int i = 0; i < workBook.getNumberOfSheets(); i++) {
  172. // 创建工作表
  173. HSSFSheet sheet = workBook.getSheetAt(i);
  174. int rows = sheet.getPhysicalNumberOfRows(); // 获得行数
  175. if (rows > 0) {
  176. sheet.getMargin(HSSFSheet.TopMargin);
  177. List list=new ArrayList();
  178. for (int r = 0; r < rows; r++) { // 行循环
  179. HSSFRow row = sheet.getRow(r);
  180. if (row != null && r != 0 && r != 1) {// 不取第一行、第二行
  181. int cells = row.getLastCellNum();// 获得列数
  182. // 定义集合datas用于存Excel中一个行的数据
  183. Vector datas = new Vector();
  184. String[]arr=new String[cells];
  185. List<String>paramList=new ArrayList<String>();
  186. for (short c = 0; c < cells; c++) { // 列循环
  187. HSSFCell cell = row.getCell(c);
  188. if (cell != null) {
  189. String value = getValue(cell);
  190. // System.out.println("第" + r + "行 " + "第" + c + "列:" + value);
  191. datas.add(value);
  192. paramList.add(value);
  193. arr[c]=value;
  194. }
  195. }
  196. list.add(arr);
  197. result = fillMap(list);
  198. // dataIntoDb(tableName, paramList);
  199. // 向表中插入数据
  200. // DBFactory.insertData(dbConn, tableName, datas);
  201. }
  202. }
  203. } else {
  204. }
  205. }
  206. } catch (Exception ex) {
  207. ex.printStackTrace();
  208. log.info(ex);
  209. throw ex;
  210. }
  211. return result;
  212. }
  213. public String getValue2007(XSSFCell cell) {
  214. String value = "";
  215. switch (cell.getCellType()) {
  216. case Cell.CELL_TYPE_STRING:
  217. // System.out.println(cell.getRichStringCellValue().getString());
  218. break;
  219. case Cell.CELL_TYPE_NUMERIC:
  220. if (DateUtil.isCellDateFormatted(cell)) {
  221. // System.out.println(cell.getDateCellValue());
  222. java.util.Date date = cell.getDateCellValue();
  223. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  224. value = format.format(date);
  225. } else {
  226. // System.out.println(cell.getNumericCellValue());
  227. value = String.valueOf(cell.getNumericCellValue());
  228. }
  229. break;
  230. case Cell.CELL_TYPE_BOOLEAN:
  231. // System.out.println(cell.getBooleanCellValue());
  232. value = " " + cell.getBooleanCellValue();
  233. break;
  234. case Cell.CELL_TYPE_FORMULA:
  235. // System.out.println(cell.getCellFormula());
  236. value = cell.getCellFormula();
  237. break;
  238. default:
  239. System.out.println();
  240. }
  241. return value;
  242. }
  243. /**
  244. * 获取Excel中某个单元格的值
  245. *
  246. * @param cell
  247. * @return
  248. * @throws ParseException
  249. */
  250. @SuppressWarnings("deprecation")
  251. public String getValue(HSSFCell cell) throws ParseException {
  252. String value = "";
  253. switch (cell.getCellType()) {
  254. case HSSFCell.CELL_TYPE_NUMERIC: // 数值型
  255. System.out.println("数字类型");
  256. if (HSSFDateUtil.isCellDateFormatted(cell)) {
  257. // 如果是date类型则 ,获取该cell的date值
  258. value = HSSFDateUtil.getJavaDate(cell.getNumericCellValue())
  259. .toString();
  260. java.util.Date date1 = new Date(value);
  261. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  262. value = format.format(date1);
  263. } else {// 纯数字
  264. value = String.valueOf(cell.getNumericCellValue()).split("[.]")[0];
  265. }
  266. break;
  267. /* 此行表示单元格的内容为string类型 */
  268. case HSSFCell.CELL_TYPE_STRING: // 字符串型
  269. value = cell.getStringCellValue();
  270. break;
  271. case HSSFCell.CELL_TYPE_FORMULA:// 公式型
  272. // 读公式计算值
  273. value = String.valueOf(cell.getNumericCellValue());
  274. if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串
  275. value = cell.getStringCellValue().toString();
  276. }
  277. cell.getCellFormula();
  278. break;
  279. case HSSFCell.CELL_TYPE_BOOLEAN:// 布尔
  280. value = " " + cell.getBooleanCellValue();
  281. break;
  282. /* 此行表示该单元格值为空 */
  283. case HSSFCell.CELL_TYPE_BLANK: // 空值
  284. value = "";
  285. break;
  286. case HSSFCell.CELL_TYPE_ERROR: // 故障
  287. value = "";
  288. break;
  289. default:
  290. value = cell.getStringCellValue().toString();
  291. }
  292. return value;
  293. }
  294. // public boolean dataIntoDb(String tabName,List<String>list) throws ClassNotFoundException, SQLException{
  295. // Class.forName("dm.jdbc.driver.DmDriver");
  296. // Connection conn = DriverManager.getConnection("jdbc:dm://192.168.1.16:5236","NWYJ","NWYJ123456");
  297. // 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(?,?,?,?,?,?,?,?)";
  298. // PreparedStatement ps=null;
  299. // conn.setAutoCommit(false);
  300. // ps = conn.prepareStatement(sql);
  301. // ps.setString(1, (long) ((Math.random()+1)*1000000000)+"");
  302. // ps.setString(2, list.get(0));
  303. // ps.setString(3,list.get(1));
  304. // ps.setString(4, list.get(2));
  305. // ps.setString(5, list.get(3));
  306. // ps.setString(6, list.get(4));
  307. // ps.setString(7, list.get(5));
  308. // ps.setString(8,list.get(6));
  309. // int k=ps.executeUpdate();
  310. // conn.commit();
  311. //// System.out.println("k====="+k);
  312. // return false;
  313. // }
  314. /**
  315. * 将界面传输过来的数据保存到数据库
  316. * @param params
  317. * @return
  318. * @throws ClassNotFoundException
  319. */
  320. @SuppressWarnings("static-access")
  321. @ProduceMime("application/json")
  322. @POST
  323. @Path("/UPSGeneratorToDb")
  324. public Msg UPSGeneratorToDb(String params) throws ClassNotFoundException{
  325. Msg m=new Msg();
  326. String json = Utils.getParameter("json", params) == null ? "" : Utils.getParameter(
  327. "json", params);
  328. log.info("json===" + json);
  329. String classId = Utils.getParameter("classId", params) == null ? "" : Utils
  330. .getParameter("classId", params);
  331. log.info("classId===" + classId);
  332. json=json.replace("_"+classId, "");
  333. Connection conn = null;
  334. PreparedStatement st = null;
  335. DbConnection db = new DbConnection();
  336. List<GeneratorBean> list = JsonPluginsUtil.jsonToBeanList(json, GeneratorBean.class);
  337. String sql="INSERT INTO EMC_AM_UPS_GENERATOR (FD_OBJECTID,COMP_ID,COMP,NAME,MODEL_TYPE,VOLTAGE_LEVEL,CONTENT,NUM,PRICE"
  338. + "GAS,PROVIDER,BUY_DATE,STORE_PLACE,INPIRE,OFFICE_TEL,MOBILE_PHONE,IS_USED,USED_STAT,UPDATEDATE,IS_DEL) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
  339. try {
  340. conn = db.getConnection();
  341. int num=0;
  342. conn.setAutoCommit(false);
  343. st = conn.prepareStatement(sql);
  344. for(int i=0;i<list.size();i++){
  345. GeneratorBean eb=list.get(i);
  346. // log.info(" eb.getEXPERT_AREA()===="+ eb.getCOMP());
  347. st.setString(1, createMsgId(getMsgId()));
  348. st.setString(2, "");
  349. // st.setString(3, eb.getCOMP());
  350. st.setString(4, eb.getNAME());
  351. st.setString(5, eb.getMODEL_TYPE());
  352. st.setString(6, eb.getVOLTAGE_LEVEL());
  353. st.setString(7, eb.getCONTENT());
  354. st.setString(8, eb.getNUM());
  355. st.setString(9, eb.getPRICE());
  356. st.setString(10, eb.getGAS());
  357. st.setString(11, eb.getPROVIDER());
  358. st.setString(12, eb.getBUY_DATE());
  359. st.setString(13, eb.getSTORE_PLACE());
  360. st.setString(14, eb.getINPIRE());
  361. st.setString(15, eb.getOFFICE_TEL());
  362. st.setString(16, eb.getMOBILE_PHONE());
  363. st.setString(17, eb.getIS_USED());
  364. st.setString(18, eb.getUSED_STAT());
  365. st.setString(19, formatDate(new Date()));
  366. st.setString(20, "0");
  367. st.executeUpdate();
  368. num++;
  369. }
  370. if(num==list.size()){
  371. log.info("保存成功");
  372. conn.commit();
  373. m.setSucsess(new Boolean(true).toString());
  374. m.setInfo(Parameter.DELETE_SUCSESS);
  375. return m;
  376. }else{
  377. m.setSucsess(new Boolean(false).toString());
  378. m.setInfo(Parameter.DELETE_FAILURE);
  379. // st.executeBatch();
  380. conn.rollback();
  381. log.info("保存失败");
  382. return m;
  383. }
  384. } catch (SQLException e) {
  385. this.log.error(e.getMessage(), e);
  386. throw new ClassNotFoundException("DAO Layou: 消息保存", e);
  387. } finally {
  388. db.close(st);
  389. db.close(conn);
  390. }
  391. }
  392. public String formatDate(Date d) {
  393. SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
  394. String date = sd.format(d);
  395. return date;
  396. }
  397. @SuppressWarnings({ "unchecked", "rawtypes" })
  398. public List<String> getMsgId() throws ClassNotFoundException {
  399. String sql = "SELECT FD_OBJECTID FROM EMC_AM_UPS_GENERATOR";
  400. Connection conn = null;
  401. Statement stat = null;
  402. ResultSet rs = null;
  403. DbConnection db = new DbConnection();
  404. try {
  405. conn = db.getConnection();
  406. stat = conn.createStatement();
  407. rs = stat.executeQuery(sql);
  408. List<String> list = new ArrayList();
  409. while (rs.next()) {
  410. list.add(rs.getString("FD_OBJECTID"));
  411. }
  412. return list;
  413. } catch (SQLException e) {
  414. // this.log.error(e.getMessage(), e);
  415. throw new ClassNotFoundException("DAO Layou: 获得数据库消息ID集合"
  416. + sql, e);
  417. } finally {
  418. db.close(rs);
  419. db.close(stat);
  420. db.close(conn);
  421. }
  422. }
  423. public String createMsgId(List<String> list) throws ClassNotFoundException{
  424. long l=(long) ((Math.random()+1)*1000000000);
  425. String msgId=l+"";
  426. if(list.contains(msgId)){
  427. return createMsgId(list);
  428. }
  429. else{
  430. // log.info("msgid==="+msgId);
  431. return msgId;
  432. }
  433. }
  434. }