390d4858958e86566a127129691261fd0c26cea4.svn-base 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. package com.sinosoft.common.excel;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.IOException;
  5. import java.io.UnsupportedEncodingException;
  6. import java.sql.Connection;
  7. import java.sql.PreparedStatement;
  8. import java.sql.ResultSet;
  9. import java.sql.SQLException;
  10. import java.sql.Statement;
  11. import java.text.DateFormat;
  12. import java.text.ParseException;
  13. import java.text.SimpleDateFormat;
  14. import java.util.ArrayList;
  15. import java.util.Date;
  16. import java.util.HashMap;
  17. import java.util.Iterator;
  18. import java.util.List;
  19. import java.util.Map;
  20. import java.util.Vector;
  21. import javax.servlet.http.HttpServletRequest;
  22. import javax.servlet.http.HttpServletResponse;
  23. import javax.ws.rs.POST;
  24. import javax.ws.rs.Path;
  25. import javax.ws.rs.ProduceMime;
  26. import javax.ws.rs.core.Context;
  27. import org.apache.log4j.Logger;
  28. import org.apache.poi.hssf.usermodel.HSSFCell;
  29. import org.apache.poi.hssf.usermodel.HSSFDateUtil;
  30. import org.apache.poi.hssf.usermodel.HSSFRow;
  31. import org.apache.poi.hssf.usermodel.HSSFSheet;
  32. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  33. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  34. import org.apache.poi.ss.usermodel.Cell;
  35. import org.apache.poi.ss.usermodel.DateUtil;
  36. import org.apache.poi.xssf.usermodel.XSSFCell;
  37. import org.apache.poi.xssf.usermodel.XSSFRow;
  38. import org.apache.poi.xssf.usermodel.XSSFSheet;
  39. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  40. import com.formaction.Parameter;
  41. import com.formaction.Utils;
  42. import com.formaction.vo.Msg;
  43. import com.persistence.DbConnection;
  44. import com.sinosoft.common.upLoad.service.UploadManageImpl;
  45. import com.sinosoft.lz.system.util.JsonUtil;
  46. /**
  47. * 读取Excel将数据返回到頁面
  48. *
  49. * @author 彭志超
  50. *
  51. */
  52. @Path("/StandardExcelToDBTableTool/")
  53. public class StandardExcelToDBTableTool {
  54. private static final Logger log = Logger.getLogger(StandardExcelToDBTableTool.class);
  55. @ProduceMime("text/html")
  56. @POST
  57. @Path("/importFile")
  58. public String importFile(@Context HttpServletRequest request,
  59. @Context HttpServletResponse response) throws Exception{//新增保存
  60. // Msg m=new Msg();
  61. UploadManageImpl upload2 = new UploadManageImpl();
  62. String path = upload2.uploadFilePath(request, response);
  63. String result="";
  64. log.info("saveFile.path===="+path);
  65. if("success".equals(path.split(";")[1])){
  66. //将数据返回到界面
  67. path=path.split(";")[2];
  68. // String report_type=request.getParameter("report_type");
  69. StandardExcelToDBTableTool xte = new StandardExcelToDBTableTool();
  70. result=xte.readExcelByName(path);
  71. }else{
  72. //返回失败信息
  73. result="";
  74. }
  75. log.info("result======"+result);
  76. return result;
  77. }
  78. public String readExcelByName(String fileName) throws Exception {
  79. StandardExcelToDBTableTool tool = new StandardExcelToDBTableTool();
  80. // String fileName=Utils.getParameter("fileName", params) == null ? "" : Utils.getParameter(
  81. // "fileName", params);
  82. // String fileName="E:\\javaDemo\\person.xls";
  83. int i=fileName.lastIndexOf(".");
  84. String type=fileName.substring(i+1);
  85. log.info("fileName===="+fileName);
  86. String result="";
  87. if("xls".equals(type)){
  88. result=tool.readExcel(fileName,"person");
  89. }else if("xlsx".equals(type)){
  90. result= tool.readExcel2007(fileName,"person");
  91. }
  92. result="{\"rows\":"+result+"}";
  93. log.info(result);
  94. return result;
  95. }
  96. // public void readExcel2007(DBModel dbConn, String filePath, String tableName)
  97. @SuppressWarnings({ "unused", "rawtypes", "unchecked", "resource" })
  98. public String readExcel2007( String filePath, String tableName)
  99. throws Exception {
  100. String result="";
  101. try {
  102. // InputStream inp = new FileInputStream(filePath);
  103. // Workbook wb = WorkbookFactory.create(inp);
  104. XSSFWorkbook wb = new XSSFWorkbook(filePath);
  105. int sheetSize = wb.getNumberOfSheets();
  106. // for (int i = 0; i < sheetSize; i++) {
  107. List list=new ArrayList();
  108. XSSFSheet sheet = wb.getSheetAt(0);
  109. // Sheet sheet = wb.getSheetAt(i);
  110. for (Iterator rit = sheet.rowIterator(); rit.hasNext();) {
  111. // 迭代行
  112. XSSFRow row = (XSSFRow) rit.next();
  113. // 迭代单元格
  114. Vector datas = new Vector();
  115. StringBuffer sb=new StringBuffer();
  116. Map<String, String>lineMap=new HashMap<String, String>();
  117. for (Iterator cit = row.cellIterator(); cit.hasNext();) {
  118. // 定义集合datas用于存Excel中一个行的数据
  119. XSSFCell cell = (XSSFCell) cit.next();
  120. String value = getValue2007(cell);
  121. sb.append(value+"|");
  122. // 注意行和列是基于0索引的
  123. // System.out.print(cell.getRowIndex() + ":" + cell.getColumnIndex() + " ");
  124. datas.add(value);
  125. // System.out.println();
  126. // 开始操作单元格
  127. }
  128. String[] arr=sb.toString().split("[|]");
  129. list.add(arr);
  130. // result = fillMap(list);;
  131. // 向表中插入数据
  132. // DBFactory.insertData(dbConn, tableName, datas);
  133. }
  134. result = fillMap(list);
  135. System.out.println(result);
  136. // }
  137. } catch (FileNotFoundException e) {
  138. e.printStackTrace();
  139. throw e;
  140. } catch (IOException e) {
  141. e.printStackTrace();
  142. throw e;
  143. }
  144. return result;
  145. }
  146. /**
  147. * 將数据转换成json
  148. * @param list
  149. * @return
  150. * @throws UnsupportedEncodingException
  151. */
  152. public String fillMap(List<String[]> list) throws UnsupportedEncodingException{
  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. // String[] CLASSES_242 = arr[0]==null ? null:arr[0].split(":");
  158. // tempMap.put("COMP_ID_265", arr[0]);
  159. // if(CLASSES_242!=null)
  160. tempMap.put("CLASSES_242",new String(java.net.URLEncoder.encode(arr[0]==null ? "":arr[0].replace("国际标准", "1").replace("国家标准", "2").replace("行业标准", "3").replace("企业标准", "4"), "UTF-8").getBytes(), "ISO-8859-1"));
  161. // else
  162. // tempMap.put("CLASSES_242","");
  163. tempMap.put("DISPATCH_UNIT_242",new String(java.net.URLEncoder.encode(arr[1]==null ? "":arr[1].replace("\n", ""), "UTF-8").getBytes(), "ISO-8859-1"));
  164. // tempMap.put("AUSPICE_DEPT_242", new String(java.net.URLEncoder.encode(arr[2]==null ? "":arr[2].replace("\n", ""), "UTF-8").getBytes(), "ISO-8859-1"));
  165. tempMap.put("STANDARD_NAME_242", new String(java.net.URLEncoder.encode(arr[2]==null ? "":arr[2].replace("\n", ""), "UTF-8").getBytes(), "ISO-8859-1"));
  166. tempMap.put("STANDARD_CODE_242", new String(java.net.URLEncoder.encode(arr[3]==null ? "":arr[3].replace("\n", ""), "UTF-8").getBytes(), "ISO-8859-1"));
  167. tempMap.put("PRINT_DATE_242", new String(java.net.URLEncoder.encode(arr[4]==null ? "":arr[4].replace("\n", ""), "UTF-8").getBytes(), "ISO-8859-1"));
  168. tempMap.put("IMPLEMENT_DATE_242", new String(java.net.URLEncoder.encode(arr[5]==null ? "":arr[5].replace("\n", ""), "UTF-8").getBytes(), "ISO-8859-1"));
  169. tempMap.put("DESCRIPTION_242", new String(java.net.URLEncoder.encode(arr[6]==null ? "":arr[6].replace("\n", ""), "UTF-8").getBytes(), "ISO-8859-1"));
  170. dataList.add(tempMap);
  171. }
  172. String result=JsonUtil.list2json(dataList);
  173. return result;
  174. }
  175. /**
  176. * 将Excel数据导入到表中
  177. *
  178. * @param filePath
  179. * Excel路径
  180. * @param tableName
  181. * 表名
  182. */
  183. // public void readExcel(DBModel dbConn, String filePath, String tableName)
  184. @SuppressWarnings({ "deprecation", "unchecked", "rawtypes", "resource" })
  185. public String readExcel( String filePath, String tableName)
  186. throws Exception {
  187. String result="";
  188. try {
  189. POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream( filePath));
  190. // 创建工作簿
  191. HSSFWorkbook workBook = new HSSFWorkbook(fs);
  192. log.info(workBook.getNumberOfSheets());
  193. // System.out.println("工作表个数 :" + workBook.getNumberOfSheets());
  194. for (int i = 0; i < workBook.getNumberOfSheets(); i++) {
  195. // 创建工作表
  196. HSSFSheet sheet = workBook.getSheetAt(i);
  197. int rows = sheet.getPhysicalNumberOfRows(); // 获得行数
  198. if (rows > 0) {
  199. sheet.getMargin(HSSFSheet.TopMargin);
  200. List list=new ArrayList();
  201. for (int r = 0; r < rows; r++) { // 行循环
  202. HSSFRow row = sheet.getRow(r);
  203. if (row != null && r != 0 && r != 1) {// 不取第一行,第二行
  204. int cells = row.getLastCellNum();// 获得列数
  205. // 定义集合datas用于存Excel中一个行的数据
  206. Vector datas = new Vector();
  207. String[]arr=new String[cells];
  208. List<String>paramList=new ArrayList<String>();
  209. for (short c = 0; c < cells; c++) { // 列循环
  210. HSSFCell cell = row.getCell(c);
  211. if (cell != null) {
  212. String value = getValue(cell);
  213. // System.out.println("第" + r + "行 " + "第" + c + "列:" + value);
  214. datas.add(value);
  215. paramList.add(value);
  216. arr[c]=value;
  217. }
  218. }
  219. list.add(arr);
  220. result = fillMap(list);
  221. // dataIntoDb(tableName, paramList);
  222. // 向表中插入数据
  223. // DBFactory.insertData(dbConn, tableName, datas);
  224. }
  225. }
  226. } else {
  227. }
  228. }
  229. } catch (Exception ex) {
  230. ex.printStackTrace();
  231. log.info(ex);
  232. throw ex;
  233. }
  234. return result;
  235. }
  236. public String getValue2007(XSSFCell cell) {
  237. String value = "";
  238. switch (cell.getCellType()) {
  239. case Cell.CELL_TYPE_STRING:
  240. // System.out.println(cell.getRichStringCellValue().getString());
  241. break;
  242. case Cell.CELL_TYPE_NUMERIC:
  243. if (DateUtil.isCellDateFormatted(cell)) {
  244. // System.out.println(cell.getDateCellValue());
  245. java.util.Date date = cell.getDateCellValue();
  246. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  247. value = format.format(date);
  248. } else {
  249. // System.out.println(cell.getNumericCellValue());
  250. value = String.valueOf(cell.getNumericCellValue());
  251. }
  252. break;
  253. case Cell.CELL_TYPE_BOOLEAN:
  254. // System.out.println(cell.getBooleanCellValue());
  255. value = " " + cell.getBooleanCellValue();
  256. break;
  257. case Cell.CELL_TYPE_FORMULA:
  258. // System.out.println(cell.getCellFormula());
  259. value = cell.getCellFormula();
  260. break;
  261. default:
  262. System.out.println();
  263. }
  264. return value;
  265. }
  266. /**
  267. * 获取Excel中某个单元格的值
  268. *
  269. * @param cell
  270. * @return
  271. * @throws ParseException
  272. */
  273. public String getValue(HSSFCell cell) throws ParseException {
  274. String value = "";
  275. String value1 = "";
  276. switch (cell.getCellType()) {
  277. case HSSFCell.CELL_TYPE_NUMERIC: // 数值型
  278. System.out.println("数字类型");
  279. if (HSSFDateUtil.isCellDateFormatted(cell)) {
  280. log.info("时间类型=============");
  281. // 如果是date类型则 ,获取该cell的date值
  282. Date d = cell.getDateCellValue();
  283. log.info(d);
  284. DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  285. value = format.format(d);
  286. } else
  287. {// 纯数字
  288. cell.setCellType(Cell.CELL_TYPE_STRING);
  289. value = cell.getStringCellValue();
  290. }
  291. break;
  292. /* 此行表示单元格的内容为string类型 */
  293. case HSSFCell.CELL_TYPE_STRING: // 字符串型
  294. value = cell.getStringCellValue();
  295. break;
  296. case HSSFCell.CELL_TYPE_FORMULA:// 公式型
  297. // 读公式计算值
  298. value = String.valueOf(cell.getNumericCellValue());
  299. if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串
  300. value = cell.getStringCellValue().toString();
  301. }
  302. cell.getCellFormula();
  303. break;
  304. case HSSFCell.CELL_TYPE_BOOLEAN:// 布尔
  305. value = " " + cell.getBooleanCellValue();
  306. break;
  307. /* 此行表示该单元格值为空 */
  308. case HSSFCell.CELL_TYPE_BLANK: // 空值
  309. value = "";
  310. break;
  311. case HSSFCell.CELL_TYPE_ERROR: // 故障
  312. value = "";
  313. break;
  314. default:
  315. value = cell.getStringCellValue().toString();
  316. }
  317. return value;
  318. }
  319. // public boolean dataIntoDb(String tabName,List<String>list) throws ClassNotFoundException, SQLException{
  320. // Class.forName("dm.jdbc.driver.DmDriver");
  321. // Connection conn = DriverManager.getConnection("jdbc:dm://192.168.1.16:5236","NWYJ","NWYJ123456");
  322. // 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(?,?,?,?,?,?,?,?)";
  323. // PreparedStatement ps=null;
  324. // conn.setAutoCommit(false);
  325. // ps = conn.prepareStatement(sql);
  326. // ps.setString(1, (long) ((Math.random()+1)*1000000000)+"");
  327. // ps.setString(2, list.get(0));
  328. // ps.setString(3,list.get(1));
  329. // ps.setString(4, list.get(2));
  330. // ps.setString(5, list.get(3));
  331. // ps.setString(6, list.get(4));
  332. // ps.setString(7, list.get(5));
  333. // ps.setString(8,list.get(6));
  334. // int k=ps.executeUpdate();
  335. // conn.commit();
  336. //// System.out.println("k====="+k);
  337. // return false;
  338. // }
  339. /**
  340. * 将界面传输过来的数据保存到数据库
  341. * @param params
  342. * @return
  343. * @throws ClassNotFoundException
  344. */
  345. @SuppressWarnings("static-access")
  346. @ProduceMime("application/json")
  347. @POST
  348. @Path("/standardToDb")
  349. public Msg standardToDb(String params) throws ClassNotFoundException{
  350. Msg m=new Msg();
  351. String json = Utils.getParameter("json", params) == null ? "" : Utils.getParameter(
  352. "json", params);
  353. log.info("json===" + json);
  354. String classId = Utils.getParameter("classId", params) == null ? "" : Utils
  355. .getParameter("classId", params);
  356. log.info("classId===" + classId);
  357. //部门
  358. String deptId = Utils.getParameter("deptId", params) == null ? "" : Utils
  359. .getParameter("deptId", params);
  360. log.info("deptId===" + deptId);
  361. //单位
  362. String compid = Utils.getParameter("compid", params) == null ? "" : Utils
  363. .getParameter("compid", params);
  364. log.info("compid===" + compid);
  365. //录入人
  366. String userid = Utils.getParameter("userId", params) == null ? "" : Utils
  367. .getParameter("userId", params);
  368. log.info("userid===" + userid);
  369. json=json.replace("_"+classId, "");
  370. Connection conn = null;
  371. PreparedStatement st = null;
  372. DbConnection db = new DbConnection();
  373. List<StandardBead> list = JsonPluginsUtil.jsonToBeanList(json, StandardBead.class);
  374. String sql="INSERT INTO EMC_AM_NATIONAL_VOCATION_STANDARD (FD_OBJECTID,CLASSES,DISPATCH_UNIT,AUSPICE_DEPT,STANDARD_NAME,STANDARD_CODE,"
  375. + "PRINT_DATE,IMPLEMENT_DATE,STATE,DESCRIPTION,TYPEIN_PEOPLE,TYPEIN_TIME,UNITE,DEPT,OBJ_FIRST,COLUMN_1,"
  376. + "COLUMN_2,COLUMN_3,COLUMN_4,IS_DEL,UPDATEDATE) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
  377. try {
  378. conn = db.getConnection();
  379. int num=0;
  380. conn.setAutoCommit(false);
  381. st = conn.prepareStatement(sql);
  382. for(int i=0;i<list.size();i++){
  383. StandardBead eb=list.get(i);
  384. log.info("eb.getCLASSES()===="+ eb.getCLASSES());
  385. st.setString(1, createMsgId(getMsgId()));
  386. st.setString(2, eb.getCLASSES() );
  387. st.setString(3, eb.getDISPATCH_UNIT() );
  388. st.setString(4, eb.getAUSPICE_DEPT() );
  389. st.setString(5, eb.getSTANDARD_NAME() );
  390. st.setString(6, eb.getSTANDARD_CODE() );
  391. st.setString(7, eb.getPRINT_DATE() );
  392. st.setString(8, eb.getIMPLEMENT_DATE() );
  393. st.setString(9, "1");
  394. st.setString(10, eb.getDESCRIPTION() );
  395. st.setString(11, userid);
  396. st.setString(12, formatDate2(new Date()));
  397. st.setString(13, compid);
  398. st.setString(14, deptId);
  399. st.setString(15, "0");
  400. st.setString(16, "0");
  401. st.setString(17, "0");
  402. st.setString(18, "0");
  403. st.setString(19, "0");
  404. st.setString(20, "0");
  405. st.setString(21, formatDate(new Date()));
  406. st.executeUpdate();
  407. num++;
  408. }
  409. if(num==list.size()){
  410. log.info("保存成功");
  411. conn.commit();
  412. m.setSucsess(new Boolean(true).toString());
  413. m.setInfo(Parameter.DELETE_SUCSESS);
  414. return m;
  415. }else{
  416. m.setSucsess(new Boolean(false).toString());
  417. m.setInfo(Parameter.DELETE_FAILURE);
  418. // st.executeBatch();
  419. conn.rollback();
  420. log.info("保存失败");
  421. return m;
  422. }
  423. } catch (SQLException e) {
  424. this.log.error(e.getMessage(), e);
  425. throw new ClassNotFoundException("DAO Layou: 消息保存", e);
  426. } finally {
  427. db.close(st);
  428. db.close(conn);
  429. }
  430. }
  431. public String formatDate(Date d) {
  432. SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  433. String date = sd.format(d);
  434. return date;
  435. }
  436. public String formatDate2(Date d) {
  437. SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
  438. String date = sd.format(d);
  439. return date;
  440. }
  441. @SuppressWarnings({ "unchecked", "rawtypes" })
  442. public List<String> getMsgId() throws ClassNotFoundException {
  443. String sql = "SELECT FD_OBJECTID FROM EMC_AM_NATIONAL_VOCATION_STANDARD";
  444. Connection conn = null;
  445. Statement stat = null;
  446. ResultSet rs = null;
  447. DbConnection db = new DbConnection();
  448. try {
  449. conn = db.getConnection();
  450. stat = conn.createStatement();
  451. rs = stat.executeQuery(sql);
  452. List<String> list = new ArrayList();
  453. while (rs.next()) {
  454. list.add(rs.getString("FD_OBJECTID"));
  455. }
  456. return list;
  457. } catch (SQLException e) {
  458. // this.log.error(e.getMessage(), e);
  459. throw new ClassNotFoundException("DAO Layou: 获得数据库消息ID集合"
  460. + sql, e);
  461. } finally {
  462. db.close(rs);
  463. db.close(stat);
  464. db.close(conn);
  465. }
  466. }
  467. public String createMsgId(List<String> list) throws ClassNotFoundException{
  468. long l=(long) ((Math.random()+1)*1000000000);
  469. String msgId=l+"";
  470. if(list.contains(msgId)){
  471. return createMsgId(list);
  472. }
  473. else{
  474. // log.info("msgid==="+msgId);
  475. return msgId;
  476. }
  477. }
  478. }