26c7e821196b3f98ffb7ffd5a7491fb3f5c89513.svn-base 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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("/GovernmentExcelToDBTableTool/")
  53. public class GovernmentExcelToDBTableTool {
  54. private static final Logger log = Logger.getLogger(GovernmentExcelToDBTableTool.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. GovernmentExcelToDBTableTool xte = new GovernmentExcelToDBTableTool();
  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. GovernmentExcelToDBTableTool tool = new GovernmentExcelToDBTableTool();
  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[] SECRECY_LEVEL_240 = arr[5]==null ? null:arr[5].split(":");
  158. // tempMap.put("COMP_ID_265", arr[0]);
  159. tempMap.put("CLASSES_240",new String(java.net.URLEncoder.encode(arr[0]==null ? "":arr[0], "UTF-8").getBytes(), "ISO-8859-1"));
  160. tempMap.put("DISPATCH_UNIT_240",new String(java.net.URLEncoder.encode(arr[1]==null ? "":arr[1], "UTF-8").getBytes(), "ISO-8859-1"));
  161. tempMap.put("DOCUMENT_NAME_240", new String(java.net.URLEncoder.encode(arr[2]==null ? "":arr[2], "UTF-8").getBytes(), "ISO-8859-1"));
  162. tempMap.put("DISPATCH_WORD_SIZE_240", new String(java.net.URLEncoder.encode(arr[3]==null ? "":arr[3], "UTF-8").getBytes(), "ISO-8859-1"));
  163. tempMap.put("PRINT_DATE_240", new String(java.net.URLEncoder.encode(arr[4]==null ? "":arr[4], "UTF-8").getBytes(), "ISO-8859-1"));
  164. if(SECRECY_LEVEL_240!=null)
  165. tempMap.put("SECRECY_LEVEL_240", new String(java.net.URLEncoder.encode(SECRECY_LEVEL_240[0], "UTF-8").getBytes(), "ISO-8859-1"));
  166. else
  167. tempMap.put("SECRECY_LEVEL_240", "");
  168. tempMap.put("DESCRIPTION_240", new String(java.net.URLEncoder.encode(arr[6]==null ? "":arr[6], "UTF-8").getBytes(), "ISO-8859-1"));
  169. dataList.add(tempMap);
  170. }
  171. String result=JsonUtil.list2json(dataList);
  172. return result;
  173. }
  174. /**
  175. * 将Excel数据导入到表中
  176. *
  177. * @param filePath
  178. * Excel路径
  179. * @param tableName
  180. * 表名
  181. */
  182. // public void readExcel(DBModel dbConn, String filePath, String tableName)
  183. @SuppressWarnings({ "deprecation", "unchecked", "rawtypes", "resource" })
  184. public String readExcel( String filePath, String tableName)
  185. throws Exception {
  186. String result="";
  187. try {
  188. POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream( filePath));
  189. // 创建工作簿
  190. HSSFWorkbook workBook = new HSSFWorkbook(fs);
  191. log.info(workBook.getNumberOfSheets());
  192. // System.out.println("工作表个数 :" + workBook.getNumberOfSheets());
  193. for (int i = 0; i < workBook.getNumberOfSheets(); i++) {
  194. // 创建工作表
  195. HSSFSheet sheet = workBook.getSheetAt(i);
  196. int rows = sheet.getPhysicalNumberOfRows(); // 获得行数
  197. if (rows > 0) {
  198. sheet.getMargin(HSSFSheet.TopMargin);
  199. List list=new ArrayList();
  200. for (int r = 0; r < rows; r++) { // 行循环
  201. HSSFRow row = sheet.getRow(r);
  202. if (row != null && r != 0 && r != 1) {// 不取第一行,第二行
  203. int cells = row.getLastCellNum();// 获得列数
  204. // 定义集合datas用于存Excel中一个行的数据
  205. Vector datas = new Vector();
  206. String[]arr=new String[cells];
  207. List<String>paramList=new ArrayList<String>();
  208. for (short c = 0; c < cells; c++) { // 列循环
  209. HSSFCell cell = row.getCell(c);
  210. if (cell != null) {
  211. String value = getValue(cell);
  212. // System.out.println("第" + r + "行 " + "第" + c + "列:" + value);
  213. datas.add(value);
  214. paramList.add(value);
  215. arr[c]=value;
  216. }
  217. }
  218. list.add(arr);
  219. result = fillMap(list);
  220. // dataIntoDb(tableName, paramList);
  221. // 向表中插入数据
  222. // DBFactory.insertData(dbConn, tableName, datas);
  223. }
  224. }
  225. } else {
  226. }
  227. }
  228. } catch (Exception ex) {
  229. ex.printStackTrace();
  230. log.info(ex);
  231. throw ex;
  232. }
  233. return result;
  234. }
  235. public String getValue2007(XSSFCell cell) {
  236. String value = "";
  237. switch (cell.getCellType()) {
  238. case Cell.CELL_TYPE_STRING:
  239. // System.out.println(cell.getRichStringCellValue().getString());
  240. break;
  241. case Cell.CELL_TYPE_NUMERIC:
  242. if (DateUtil.isCellDateFormatted(cell)) {
  243. // System.out.println(cell.getDateCellValue());
  244. java.util.Date date = cell.getDateCellValue();
  245. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  246. value = format.format(date);
  247. } else {
  248. // System.out.println(cell.getNumericCellValue());
  249. value = String.valueOf(cell.getNumericCellValue());
  250. }
  251. break;
  252. case Cell.CELL_TYPE_BOOLEAN:
  253. // System.out.println(cell.getBooleanCellValue());
  254. value = " " + cell.getBooleanCellValue();
  255. break;
  256. case Cell.CELL_TYPE_FORMULA:
  257. // System.out.println(cell.getCellFormula());
  258. value = cell.getCellFormula();
  259. break;
  260. default:
  261. System.out.println();
  262. }
  263. return value;
  264. }
  265. /**
  266. * 获取Excel中某个单元格的值
  267. *
  268. * @param cell
  269. * @return
  270. * @throws ParseException
  271. */
  272. public String getValue(HSSFCell cell) throws ParseException {
  273. String value = "";
  274. String value1 = "";
  275. switch (cell.getCellType()) {
  276. case HSSFCell.CELL_TYPE_NUMERIC: // 数值型
  277. System.out.println("数字类型");
  278. if (HSSFDateUtil.isCellDateFormatted(cell)) {
  279. log.info("时间类型=============");
  280. // 如果是date类型则 ,获取该cell的date值
  281. Date d = cell.getDateCellValue();
  282. log.info(d);
  283. DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  284. value = format.format(d);
  285. } else
  286. {// 纯数字
  287. cell.setCellType(Cell.CELL_TYPE_STRING);
  288. value = cell.getStringCellValue();
  289. }
  290. break;
  291. /* 此行表示单元格的内容为string类型 */
  292. case HSSFCell.CELL_TYPE_STRING: // 字符串型
  293. value = cell.getStringCellValue();
  294. break;
  295. case HSSFCell.CELL_TYPE_FORMULA:// 公式型
  296. // 读公式计算值
  297. value = String.valueOf(cell.getNumericCellValue());
  298. if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串
  299. value = cell.getStringCellValue().toString();
  300. }
  301. cell.getCellFormula();
  302. break;
  303. case HSSFCell.CELL_TYPE_BOOLEAN:// 布尔
  304. value = " " + cell.getBooleanCellValue();
  305. break;
  306. /* 此行表示该单元格值为空 */
  307. case HSSFCell.CELL_TYPE_BLANK: // 空值
  308. value = "";
  309. break;
  310. case HSSFCell.CELL_TYPE_ERROR: // 故障
  311. value = "";
  312. break;
  313. default:
  314. value = cell.getStringCellValue().toString();
  315. }
  316. return value;
  317. }
  318. // public boolean dataIntoDb(String tabName,List<String>list) throws ClassNotFoundException, SQLException{
  319. // Class.forName("dm.jdbc.driver.DmDriver");
  320. // Connection conn = DriverManager.getConnection("jdbc:dm://192.168.1.16:5236","NWYJ","NWYJ123456");
  321. // 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(?,?,?,?,?,?,?,?)";
  322. // PreparedStatement ps=null;
  323. // conn.setAutoCommit(false);
  324. // ps = conn.prepareStatement(sql);
  325. // ps.setString(1, (long) ((Math.random()+1)*1000000000)+"");
  326. // ps.setString(2, list.get(0));
  327. // ps.setString(3,list.get(1));
  328. // ps.setString(4, list.get(2));
  329. // ps.setString(5, list.get(3));
  330. // ps.setString(6, list.get(4));
  331. // ps.setString(7, list.get(5));
  332. // ps.setString(8,list.get(6));
  333. // int k=ps.executeUpdate();
  334. // conn.commit();
  335. //// System.out.println("k====="+k);
  336. // return false;
  337. // }
  338. /**
  339. * 将界面传输过来的数据保存到数据库
  340. * @param params
  341. * @return
  342. * @throws ClassNotFoundException
  343. */
  344. @SuppressWarnings("static-access")
  345. @ProduceMime("application/json")
  346. @POST
  347. @Path("/governmentToDb")
  348. public Msg governmentToDb(String params) throws ClassNotFoundException{
  349. Msg m=new Msg();
  350. String json = Utils.getParameter("json", params) == null ? "" : Utils.getParameter(
  351. "json", params);
  352. log.info("json===" + json);
  353. String classId = Utils.getParameter("classId", params) == null ? "" : Utils
  354. .getParameter("classId", params);
  355. log.info("classId===" + classId);
  356. //部门
  357. String deptId = Utils.getParameter("deptId", params) == null ? "" : Utils
  358. .getParameter("deptId", params);
  359. log.info("deptId===" + deptId);
  360. //单位
  361. String compid = Utils.getParameter("compid", params) == null ? "" : Utils
  362. .getParameter("compid", params);
  363. log.info("compid===" + compid);
  364. //录入人
  365. String userid = Utils.getParameter("userId", params) == null ? "" : Utils
  366. .getParameter("userId", params);
  367. log.info("userid===" + userid);
  368. //录入人姓名
  369. String username = Utils.getParameter("userName", params) == null ? "" : Utils
  370. .getParameter("userName", params);
  371. log.info("userName===" + username);
  372. json=json.replace("_"+classId, "");
  373. Connection conn = null;
  374. PreparedStatement st = null;
  375. DbConnection db = new DbConnection();
  376. List<GovernmentBean> list = JsonPluginsUtil.jsonToBeanList(json, GovernmentBean.class);
  377. String sql="INSERT INTO EMC_AM_GOVERNMENT_DOCUMENT (FD_OBJECTID,CLASSES,DISPATCH_UNIT,DOCUMENT_NAME,DISPATCH_WORD_SIZE,"
  378. + "PRINT_DATE,STATE,DESCRIPTION,SECRECY_LEVEL,TYPEIN_PEOPLE,TYPEIN_TIME,UNITE,DEPT,OBJ_FIRST,IS_ISSUE,"
  379. + "TYPEIN_PEOPLE_ID,IS_SHARE,IS_DEL,UPDATEDATE) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
  380. try {
  381. conn = db.getConnection();
  382. int num=0;
  383. conn.setAutoCommit(false);
  384. st = conn.prepareStatement(sql);
  385. for(int i=0;i<list.size();i++){
  386. GovernmentBean eb=list.get(i);
  387. log.info("eb.getCLASSES()===="+ eb.getCLASSES());
  388. st.setString(1, createMsgId(getMsgId()));
  389. st.setString(2, eb.getCLASSES() );
  390. st.setString(3, eb.getDISPATCH_UNIT() );
  391. st.setString(4, eb.getDOCUMENT_NAME() );
  392. st.setString(5, eb.getDISPATCH_WORD_SIZE() );
  393. st.setString(6, eb.getPRINT_DATE() );
  394. st.setString(7, "1");
  395. st.setString(8, eb.getDESCRIPTION() );
  396. st.setString(9, eb.getSECRECY_LEVEL());
  397. st.setString(10, username);
  398. st.setString(11, formatDate2(new Date()));
  399. st.setString(12, compid);
  400. st.setString(13, deptId);
  401. st.setString(14, "0");
  402. st.setString(15, "0");
  403. st.setString(16, userid);
  404. st.setString(17, "0");
  405. st.setString(18, "0");
  406. st.setString(19, formatDate(new Date()));
  407. st.executeUpdate();
  408. num++;
  409. }
  410. if(num==list.size()){
  411. log.info("保存成功");
  412. conn.commit();
  413. m.setSucsess(new Boolean(true).toString());
  414. m.setInfo(Parameter.DELETE_SUCSESS);
  415. return m;
  416. }else{
  417. m.setSucsess(new Boolean(false).toString());
  418. m.setInfo(Parameter.DELETE_FAILURE);
  419. // st.executeBatch();
  420. conn.rollback();
  421. log.info("保存失败");
  422. return m;
  423. }
  424. } catch (SQLException e) {
  425. this.log.error(e.getMessage(), e);
  426. throw new ClassNotFoundException("DAO Layou: 消息保存", e);
  427. } finally {
  428. db.close(st);
  429. db.close(conn);
  430. }
  431. }
  432. public String formatDate(Date d) {
  433. SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  434. String date = sd.format(d);
  435. return date;
  436. }
  437. public String formatDate2(Date d) {
  438. SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
  439. String date = sd.format(d);
  440. return date;
  441. }
  442. @SuppressWarnings({ "unchecked", "rawtypes" })
  443. public List<String> getMsgId() throws ClassNotFoundException {
  444. String sql = "SELECT FD_OBJECTID FROM EMC_AM_GOVERNMENT_DOCUMENT";
  445. Connection conn = null;
  446. Statement stat = null;
  447. ResultSet rs = null;
  448. DbConnection db = new DbConnection();
  449. try {
  450. conn = db.getConnection();
  451. stat = conn.createStatement();
  452. rs = stat.executeQuery(sql);
  453. List<String> list = new ArrayList();
  454. while (rs.next()) {
  455. list.add(rs.getString("FD_OBJECTID"));
  456. }
  457. return list;
  458. } catch (SQLException e) {
  459. // this.log.error(e.getMessage(), e);
  460. throw new ClassNotFoundException("DAO Layou: 获得数据库消息ID集合"
  461. + sql, e);
  462. } finally {
  463. db.close(rs);
  464. db.close(stat);
  465. db.close(conn);
  466. }
  467. }
  468. public String createMsgId(List<String> list) throws ClassNotFoundException{
  469. long l=(long) ((Math.random()+1)*1000000000);
  470. String msgId=l+"";
  471. if(list.contains(msgId)){
  472. return createMsgId(list);
  473. }
  474. else{
  475. // log.info("msgid==="+msgId);
  476. return msgId;
  477. }
  478. }
  479. }