2920463b08929e370d3c67cfc8adf019e9ff33d1.svn-base 19 KB

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