70078027ed8c9b9e470c65a809ed54e2aab37dd7.svn-base 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. package com.sinosoft.em.gps.service;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.IOException;
  5. import java.sql.Connection;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.SQLException;
  9. import java.sql.Statement;
  10. import java.text.ParseException;
  11. import java.text.SimpleDateFormat;
  12. import java.util.ArrayList;
  13. import java.util.Date;
  14. import java.util.HashMap;
  15. import java.util.Iterator;
  16. import java.util.List;
  17. import java.util.Map;
  18. import java.util.Vector;
  19. import javax.servlet.http.HttpServletRequest;
  20. import javax.servlet.http.HttpServletResponse;
  21. import javax.ws.rs.POST;
  22. import javax.ws.rs.Path;
  23. import javax.ws.rs.ProduceMime;
  24. import javax.ws.rs.core.Context;
  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.common.upLoad.service.UploadManageImpl;
  43. import com.sinosoft.common.util.JsonPluginsUtil;
  44. import com.sinosoft.lz.system.util.JsonUtil;
  45. /**
  46. * 读取Excel将数据返回到頁面
  47. *
  48. * @author 彭志超
  49. *
  50. */
  51. @Path("/BGDmingxibiao/")
  52. public class BGDmingxibiao {
  53. private static final Logger log = Logger.getLogger(BGDmingxibiao.class);
  54. @ProduceMime("application/json")
  55. @POST
  56. @Path("/importExpert")
  57. public String importExpert(@Context HttpServletRequest request,
  58. @Context HttpServletResponse response) throws Exception{//新增保存
  59. // Msg m=new Msg();
  60. UploadManageImpl upload2 = new UploadManageImpl();
  61. String path = upload2.uploadFilePath(request, response);
  62. String result="";
  63. log.info("saveFile.path===="+path);
  64. if("success".equals(path.split(";")[1])){
  65. //将数据返回到界面
  66. path=path.split(";")[2];
  67. // String report_type=request.getParameter("report_type");
  68. BGDmingxibiao xte = new BGDmingxibiao();
  69. result=xte.readExcelByName(path);
  70. }else{
  71. //返回失败信息
  72. result="";
  73. }
  74. return result;
  75. }
  76. @ProduceMime("application/json")
  77. @POST
  78. @Path("/getGeneratorCarExcel")
  79. public String readExcelByName(String fileName) throws Exception {
  80. BGDmingxibiao tool = new BGDmingxibiao();
  81. // String fileName=Utils.getParameter("fileName", params) == null ? "" : Utils.getParameter(
  82. // "fileName", params);
  83. // String fileName="E:\\javaDemo\\person.xls";
  84. int i=fileName.lastIndexOf(".");
  85. String type=fileName.substring(i+1);
  86. log.info("fileName===="+fileName);
  87. String result="";
  88. if("xls".equals(type)){
  89. result=tool.readExcel(fileName,"person");
  90. }else if("xlsx".equals(type)){
  91. result= tool.readExcel2007(fileName,"person");
  92. }
  93. result="{\"rows\":"+result+"}";
  94. log.info(result);
  95. return result;
  96. }
  97. // public void readExcel2007(DBModel dbConn, String filePath, String tableName)
  98. @SuppressWarnings({ "unused", "rawtypes", "unchecked", "resource" })
  99. public String readExcel2007( String filePath, String tableName)
  100. throws Exception {
  101. String result="";
  102. try {
  103. // InputStream inp = new FileInputStream(filePath);
  104. // Workbook wb = WorkbookFactory.create(inp);
  105. XSSFWorkbook wb = new XSSFWorkbook(filePath);
  106. int sheetSize = wb.getNumberOfSheets();
  107. // for (int i = 0; i < sheetSize; i++) {
  108. List list=new ArrayList();
  109. XSSFSheet sheet = wb.getSheetAt(0);
  110. // Sheet sheet = wb.getSheetAt(i);
  111. for (Iterator rit = sheet.rowIterator(); rit.hasNext();) {
  112. // 迭代行
  113. XSSFRow row = (XSSFRow) rit.next();
  114. // 迭代单元格
  115. Vector datas = new Vector();
  116. StringBuffer sb=new StringBuffer();
  117. Map<String, String>lineMap=new HashMap<String, String>();
  118. for (Iterator cit = row.cellIterator(); cit.hasNext();) {
  119. // 定义集合datas用于存Excel中一个行的数据
  120. XSSFCell cell = (XSSFCell) cit.next();
  121. String value = getValue2007(cell);
  122. sb.append(value+"|");
  123. // 注意行和列是基于0索引的
  124. // System.out.print(cell.getRowIndex() + ":" + cell.getColumnIndex() + " ");
  125. datas.add(value);
  126. // System.out.println();
  127. // 开始操作单元格
  128. }
  129. String[] arr=sb.toString().split("[|]");
  130. list.add(arr);
  131. // result = fillMap(list);;
  132. // 向表中插入数据
  133. // DBFactory.insertData(dbConn, tableName, datas);
  134. }
  135. result = fillMap(list);
  136. System.out.println(result);
  137. // }
  138. } catch (FileNotFoundException e) {
  139. e.printStackTrace();
  140. throw e;
  141. } catch (IOException e) {
  142. e.printStackTrace();
  143. throw e;
  144. }
  145. return result;
  146. }
  147. /**
  148. * 將数据转换成json
  149. * @param list
  150. * @return
  151. */
  152. public String fillMap(List<String[]> list){
  153. List<Map<String, String>>dataList=new ArrayList<Map<String,String>>();
  154. for(int i=0;i<list.size();i++){
  155. Map<String, String>tempMap=new HashMap<String, String>();
  156. String[]arr=list.get(i);
  157. tempMap.put("TASK_NAME_615", arr[0]);
  158. tempMap.put("TASK_TIME_615", arr[1]);
  159. tempMap.put("INPUT_MEM_615", arr[2]);
  160. tempMap.put("INPUT_CAR_615", arr[3]);
  161. tempMap.put("LEVEL_615", arr[4]);
  162. tempMap.put("DEPT_615", arr[5]);
  163. dataList.add(tempMap);
  164. }
  165. String result=JsonUtil.list2json(dataList);
  166. return result;
  167. }
  168. /**
  169. * 将Excel数据导入到表中
  170. *
  171. * @param filePath
  172. * Excel路径
  173. * @param tableName
  174. * 表名
  175. */
  176. // public void readExcel(DBModel dbConn, String filePath, String tableName)
  177. @SuppressWarnings({ "deprecation", "unchecked", "rawtypes", "resource" })
  178. public String readExcel( String filePath, String tableName)
  179. throws Exception {
  180. String result="";
  181. try {
  182. POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream( filePath));
  183. // 创建工作簿
  184. HSSFWorkbook workBook = new HSSFWorkbook(fs);
  185. log.info(workBook.getNumberOfSheets());
  186. // System.out.println("工作表个数 :" + workBook.getNumberOfSheets());
  187. for (int i = 0; i < workBook.getNumberOfSheets(); i++) {
  188. // 创建工作表
  189. HSSFSheet sheet = workBook.getSheetAt(i);
  190. int rows = sheet.getPhysicalNumberOfRows(); // 获得行数
  191. if (rows > 0) {
  192. sheet.getMargin(HSSFSheet.TopMargin);
  193. List list=new ArrayList();
  194. for (int r = 0; r < rows; r++) { // 行循环
  195. HSSFRow row = sheet.getRow(r);
  196. if (row != null && r != 0 && r != 1) {// 不取第一行,第二行
  197. int cells = row.getLastCellNum();// 获得列数
  198. // 定义集合datas用于存Excel中一个行的数据
  199. Vector datas = new Vector();
  200. String[]arr=new String[cells];
  201. List<String>paramList=new ArrayList<String>();
  202. for (short c = 0; c < cells; c++) { // 列循环
  203. HSSFCell cell = row.getCell(c);
  204. if (cell != null) {
  205. String value = getValue(cell);
  206. // System.out.println("第" + r + "行 " + "第" + c + "列:" + value);
  207. datas.add(value);
  208. paramList.add(value);
  209. arr[c]=value;
  210. }
  211. }
  212. list.add(arr);
  213. result = fillMap(list);
  214. // dataIntoDb(tableName, paramList);
  215. // 向表中插入数据
  216. // DBFactory.insertData(dbConn, tableName, datas);
  217. }
  218. }
  219. } else {
  220. }
  221. }
  222. } catch (Exception ex) {
  223. ex.printStackTrace();
  224. log.info(ex);
  225. throw ex;
  226. }
  227. return result;
  228. }
  229. public String getValue2007(XSSFCell cell) {
  230. String value = "";
  231. switch (cell.getCellType()) {
  232. case Cell.CELL_TYPE_STRING:
  233. // System.out.println(cell.getRichStringCellValue().getString());
  234. break;
  235. case Cell.CELL_TYPE_NUMERIC:
  236. if (DateUtil.isCellDateFormatted(cell)) {
  237. // System.out.println(cell.getDateCellValue());
  238. java.util.Date date = cell.getDateCellValue();
  239. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  240. value = format.format(date);
  241. } else {
  242. // System.out.println(cell.getNumericCellValue());
  243. value = String.valueOf(cell.getNumericCellValue());
  244. }
  245. break;
  246. case Cell.CELL_TYPE_BOOLEAN:
  247. // System.out.println(cell.getBooleanCellValue());
  248. value = " " + cell.getBooleanCellValue();
  249. break;
  250. case Cell.CELL_TYPE_FORMULA:
  251. // System.out.println(cell.getCellFormula());
  252. value = cell.getCellFormula();
  253. break;
  254. default:
  255. System.out.println();
  256. }
  257. return value;
  258. }
  259. /**
  260. * 获取Excel中某个单元格的值
  261. *
  262. * @param cell
  263. * @return
  264. * @throws ParseException
  265. */
  266. @SuppressWarnings("deprecation")
  267. public String getValue(HSSFCell cell) throws ParseException {
  268. String value = "";
  269. switch (cell.getCellType()) {
  270. case HSSFCell.CELL_TYPE_NUMERIC: // 数值型
  271. System.out.println("数字类型");
  272. // if (HSSFDateUtil.isCellDateFormatted(cell)) {
  273. // // 如果是date类型则 ,获取该cell的date值
  274. // value = HSSFDateUtil.getJavaDate(cell.getNumericCellValue())
  275. // .toString();
  276. // java.util.Date date1 = new Date(value);
  277. // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  278. // value = format.format(date1);
  279. // } else
  280. {// 纯数字
  281. value = String.valueOf(cell.getNumericCellValue()).split("[.]")[0];
  282. }
  283. break;
  284. /* 此行表示单元格的内容为string类型 */
  285. case HSSFCell.CELL_TYPE_STRING: // 字符串型
  286. value = cell.getStringCellValue();
  287. break;
  288. case HSSFCell.CELL_TYPE_FORMULA:// 公式型
  289. // 读公式计算值
  290. value = String.valueOf(cell.getNumericCellValue());
  291. if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串
  292. value = cell.getStringCellValue().toString();
  293. }
  294. cell.getCellFormula();
  295. break;
  296. case HSSFCell.CELL_TYPE_BOOLEAN:// 布尔
  297. value = " " + cell.getBooleanCellValue();
  298. break;
  299. /* 此行表示该单元格值为空 */
  300. case HSSFCell.CELL_TYPE_BLANK: // 空值
  301. value = "";
  302. break;
  303. case HSSFCell.CELL_TYPE_ERROR: // 故障
  304. value = "";
  305. break;
  306. default:
  307. value = cell.getStringCellValue().toString();
  308. }
  309. return value;
  310. }
  311. /**
  312. * 将界面传输过来的数据保存到数据库
  313. * @param params
  314. * @return
  315. * @throws ClassNotFoundException
  316. */
  317. @SuppressWarnings("static-access")
  318. @ProduceMime("application/json")
  319. @POST
  320. @Path("/saveBGDmingxibiao")
  321. public Msg saveBGDmingxibiao(String params) throws ClassNotFoundException{
  322. Msg m=new Msg();
  323. String json = Utils.getParameter("json", params) == null ? "" : Utils.getParameter(
  324. "json", params);
  325. log.info("json===" + json);
  326. String classId = Utils.getParameter("classId", params) == null ? "" : Utils
  327. .getParameter("classId", params);
  328. log.info("classId===" + classId);
  329. String deptId = Utils.getParameter("deptId", params) == null ? "" : Utils
  330. .getParameter("deptId", params);
  331. log.info("deptId===" + deptId);
  332. json=json.replace("_"+classId, "");
  333. Connection conn = null;
  334. PreparedStatement st = null;
  335. DbConnection db = new DbConnection();
  336. List<BGDmingxibiaoGS> list = JsonPluginsUtil.jsonToBeanList(json, BGDmingxibiaoGS.class);
  337. String sql="INSERT INTO ECM_GPS_LIST (FD_OBJECTID,TASK_NAME,TASK_TIME,INPUT_MEM,INPUT_CAR,"
  338. + "LEVEL,IS_DEL,UPDATEDATE,WRITER,WRITE_TIME,WRITE_DEPT,DEPT) 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. BGDmingxibiaoGS eb=list.get(i);
  346. log.info("eb.getDEPT()===="+ eb.getDEPT());
  347. st.setString(1, createMsgId(getMsgId()));
  348. st.setString(2, eb.getTASK_NAME() );
  349. st.setString(3, eb.getTASK_TIME() );
  350. st.setString(4, eb.getINPUT_MEM() );
  351. st.setString(5, eb.getINPUT_CAR() );
  352. st.setString(6, eb.getLEVEL() );
  353. /*st.setString(7, eb.getCAR_PRICE() );
  354. st.setString(8, eb.getCAR_GAS() );
  355. st.setString(9, eb.getCAR_PROVIDER() );
  356. st.setString(10, eb.getBUY_DATE() );
  357. st.setString(11, eb.getSTORE_PLACE() );
  358. st.setString(12, eb.getCAR_INPIRE() );
  359. st.setString(13, eb.getOFFICE_TEL() );
  360. st.setString(14, eb.getMOBILE_PHONE() );
  361. st.setString(15, eb.getIS_USED());
  362. st.setString(16, eb.getUSED_STAT());
  363. st.setString(17, deptId);
  364. st.setString(18, "0");
  365. st.setString(19, eb.getSTORED_ENERGY_TYPE());*/
  366. st.setString(20, formatDate(new Date()));
  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 ECM_GPS_LIST";
  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. }