dba05c83d38648f22ef575f2c7c3d872e5d8acf2.svn-base 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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("/ExtemalResourceExcelToDBTableTool/")
  53. public class ExtemalResourceExcelToDBTableTool {
  54. private static final Logger log = Logger.getLogger(ExtemalResourceExcelToDBTableTool.class);
  55. @ProduceMime("text/html")
  56. @POST
  57. @Path("/importExpert")
  58. public String importExpert(@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. ExtemalResourceExcelToDBTableTool xte = new ExtemalResourceExcelToDBTableTool();
  70. result=xte.readExcelByName(path);
  71. }else{
  72. //返回失败信息
  73. result="";
  74. }
  75. return result;
  76. }
  77. @ProduceMime("application/json")
  78. @POST
  79. @Path("/getExtemalResourceExcel")
  80. public String readExcelByName(String fileName) throws Exception {
  81. ExtemalResourceExcelToDBTableTool tool = new ExtemalResourceExcelToDBTableTool();
  82. // String fileName=Utils.getParameter("fileName", params) == null ? "" : Utils.getParameter(
  83. // "fileName", params);
  84. // String fileName="E:\\javaDemo\\person.xls";
  85. int i=fileName.lastIndexOf(".");
  86. String type=fileName.substring(i+1);
  87. log.info("fileName===="+fileName);
  88. String result="";
  89. if("xls".equals(type)){
  90. result=tool.readExcel(fileName,"person");
  91. }else if("xlsx".equals(type)){
  92. result= tool.readExcel2007(fileName,"person");
  93. }
  94. result="{\"rows\":"+result+"}";
  95. log.info(result);
  96. return result;
  97. }
  98. // public void readExcel2007(DBModel dbConn, String filePath, String tableName)
  99. @SuppressWarnings({ "unused", "rawtypes", "unchecked", "resource" })
  100. public String readExcel2007( String filePath, String tableName)
  101. throws Exception {
  102. String result="";
  103. try {
  104. // InputStream inp = new FileInputStream(filePath);
  105. // Workbook wb = WorkbookFactory.create(inp);
  106. XSSFWorkbook wb = new XSSFWorkbook(filePath);
  107. int sheetSize = wb.getNumberOfSheets();
  108. // for (int i = 0; i < sheetSize; i++) {
  109. List list=new ArrayList();
  110. XSSFSheet sheet = wb.getSheetAt(0);
  111. // Sheet sheet = wb.getSheetAt(i);
  112. for (Iterator rit = sheet.rowIterator(); rit.hasNext();) {
  113. // 迭代行
  114. XSSFRow row = (XSSFRow) rit.next();
  115. // 迭代单元格
  116. Vector datas = new Vector();
  117. StringBuffer sb=new StringBuffer();
  118. Map<String, String>lineMap=new HashMap<String, String>();
  119. for (Iterator cit = row.cellIterator(); cit.hasNext();) {
  120. // 定义集合datas用于存Excel中一个行的数据
  121. XSSFCell cell = (XSSFCell) cit.next();
  122. String value = getValue2007(cell);
  123. sb.append(value+"|");
  124. // 注意行和列是基于0索引的
  125. // System.out.print(cell.getRowIndex() + ":" + cell.getColumnIndex() + " ");
  126. datas.add(value);
  127. // System.out.println();
  128. // 开始操作单元格
  129. }
  130. String[] arr=sb.toString().split("[|]");
  131. list.add(arr);
  132. // result = fillMap(list);;
  133. // 向表中插入数据
  134. // DBFactory.insertData(dbConn, tableName, datas);
  135. }
  136. result = fillMap(list);
  137. System.out.println(result);
  138. // }
  139. } catch (FileNotFoundException e) {
  140. e.printStackTrace();
  141. throw e;
  142. } catch (IOException e) {
  143. e.printStackTrace();
  144. throw e;
  145. }
  146. return result;
  147. }
  148. /**
  149. * 將数据转换成json
  150. * @param list
  151. * @return
  152. * @throws UnsupportedEncodingException
  153. */
  154. public String fillMap(List<String[]> list) throws UnsupportedEncodingException{
  155. List<Map<String, String>>dataList=new ArrayList<Map<String,String>>();
  156. for(int i=0;i<list.size();i++){
  157. Map<String, String>tempMap=new HashMap<String, String>();
  158. String[]arr=list.get(i);
  159. String[] RESOURCE_TYPE_283 = arr[1]==null ? null:arr[1].split(":");
  160. tempMap.put("RESOURCE_NAME_283", new String(java.net.URLEncoder.encode(arr[0]==null ? "":arr[0], "UTF-8").getBytes(), "ISO-8859-1"));
  161. if(RESOURCE_TYPE_283!=null)
  162. tempMap.put("RESOURCE_TYPE_283", new String(java.net.URLEncoder.encode(RESOURCE_TYPE_283[0], "UTF-8").getBytes(), "ISO-8859-1"));
  163. else
  164. tempMap.put("RESOURCE_TYPE_283", "");
  165. tempMap.put("SPECIFICATION_MODEL_283", new String(java.net.URLEncoder.encode(arr[2]==null ? "":arr[2], "UTF-8").getBytes(), "ISO-8859-1"));
  166. tempMap.put("COLUMN_1_283", new String(java.net.URLEncoder.encode(arr[3]==null ? "":arr[3], "UTF-8").getBytes(), "ISO-8859-1"));
  167. tempMap.put("PARAMETER_283", new String(java.net.URLEncoder.encode(arr[4]==null ? "":arr[4], "UTF-8").getBytes(), "ISO-8859-1"));
  168. tempMap.put("NUM_283", new String(java.net.URLEncoder.encode(arr[5]==null ? "":arr[5], "UTF-8").getBytes(), "ISO-8859-1"));
  169. tempMap.put("ADDRESS_283", new String(java.net.URLEncoder.encode(arr[6]==null ? "":arr[6], "UTF-8").getBytes(), "ISO-8859-1"));
  170. // tempMap.put("SUB_UNIT_283", arr[6]);
  171. tempMap.put("LINKMAN_283", new String(java.net.URLEncoder.encode(arr[7]==null ? "":arr[7], "UTF-8").getBytes(), "ISO-8859-1"));
  172. tempMap.put("TELEPHONE_283", new String(java.net.URLEncoder.encode(arr[8]==null ? "":arr[8], "UTF-8").getBytes(), "ISO-8859-1"));
  173. tempMap.put("CELLPHONE_283", new String(java.net.URLEncoder.encode(arr[9]==null ? "":arr[9], "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. /**
  324. * 将界面传输过来的数据保存到数据库
  325. * @param params
  326. * @return
  327. * @throws ClassNotFoundException
  328. */
  329. @SuppressWarnings("static-access")
  330. @ProduceMime("application/json")
  331. @POST
  332. @Path("/extemalResourceToDb")
  333. public Msg extemalResourceToDb(String params) throws ClassNotFoundException{
  334. Msg m=new Msg();
  335. String json = Utils.getParameter("json", params) == null ? "" : Utils.getParameter(
  336. "json", params);
  337. log.info("json===" + json);
  338. String classId = Utils.getParameter("classId", params) == null ? "" : Utils
  339. .getParameter("classId", params);
  340. log.info("classId===" + classId);
  341. String deptId = Utils.getParameter("deptId", params) == null ? "" : Utils
  342. .getParameter("deptId", params);
  343. log.info("deptId===" + deptId);
  344. String userId = Utils.getParameter("userid", params) == null ? "" : Utils
  345. .getParameter("userid", params);
  346. log.info("userId===" + userId);
  347. json=json.replace("_"+classId, "");
  348. Connection conn = null;
  349. PreparedStatement st = null;
  350. DbConnection db = new DbConnection();
  351. List<ExtemalResourceBean> list = JsonPluginsUtil.jsonToBeanList(json, ExtemalResourceBean.class);
  352. String sql="INSERT INTO EMC_AM_EXTEMAL_RESOURCES (FD_OBJECTID,RESOURCE_NAME,RESOURCE_TYPE,SPECIFICATION_MODEL,"
  353. + "PARAMETER,NUM,ADDRESS,SUB_UNIT,LINKMAN,TELEPHONE,CELLPHONE,IS_DEL,UPDATEDATE,COLUMN_1,TYPEIN_PEOPLE) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
  354. try {
  355. conn = db.getConnection();
  356. int num=0;
  357. conn.setAutoCommit(false);
  358. st = conn.prepareStatement(sql);
  359. for(int i=0;i<list.size();i++){
  360. ExtemalResourceBean eb=list.get(i);
  361. log.info(" eb.getRESOURCE_NAME()===="+ eb.getRESOURCE_NAME());
  362. st.setString(1, createMsgId(getMsgId()));
  363. st.setString(2, eb.getRESOURCE_NAME());
  364. st.setString(3, eb.getRESOURCE_TYPE());
  365. st.setString(4, eb.getSPECIFICATION_MODEL());
  366. st.setString(5, eb.getPARAMETER());
  367. st.setString(6, eb.getNUM());
  368. st.setString(7, eb.getADDRESS());
  369. // st.setString(8, eb.getSUB_UNIT());
  370. st.setString(8, deptId);
  371. st.setString(9, eb.getLINKMAN());
  372. st.setString(10, eb.getTELEPHONE());
  373. st.setString(11, eb.getCELLPHONE());
  374. st.setString(12, "0");
  375. st.setString(13, formatDate(new Date()));
  376. st.setString(14, eb.getCOMP());
  377. st.setString(15, userId);
  378. st.executeUpdate();
  379. num++;
  380. }
  381. if(num==list.size()){
  382. log.info("保存成功");
  383. conn.commit();
  384. m.setSucsess(new Boolean(true).toString());
  385. m.setInfo(Parameter.DELETE_SUCSESS);
  386. return m;
  387. }else{
  388. m.setSucsess(new Boolean(false).toString());
  389. m.setInfo(Parameter.DELETE_FAILURE);
  390. // st.executeBatch();
  391. conn.rollback();
  392. log.info("保存失败");
  393. return m;
  394. }
  395. } catch (SQLException e) {
  396. this.log.error(e.getMessage(), e);
  397. throw new ClassNotFoundException("DAO Layou: 消息保存", e);
  398. } finally {
  399. db.close(st);
  400. db.close(conn);
  401. }
  402. }
  403. public String formatDate(Date d) {
  404. SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
  405. String date = sd.format(d);
  406. return date;
  407. }
  408. @SuppressWarnings({ "unchecked", "rawtypes" })
  409. public List<String> getMsgId() throws ClassNotFoundException {
  410. String sql = "SELECT FD_OBJECTID FROM EMC_AM_EXTEMAL_RESOURCES";
  411. Connection conn = null;
  412. Statement stat = null;
  413. ResultSet rs = null;
  414. DbConnection db = new DbConnection();
  415. try {
  416. conn = db.getConnection();
  417. stat = conn.createStatement();
  418. rs = stat.executeQuery(sql);
  419. List<String> list = new ArrayList();
  420. while (rs.next()) {
  421. list.add(rs.getString("FD_OBJECTID"));
  422. }
  423. return list;
  424. } catch (SQLException e) {
  425. // this.log.error(e.getMessage(), e);
  426. throw new ClassNotFoundException("DAO Layou: 获得数据库消息ID集合"
  427. + sql, e);
  428. } finally {
  429. db.close(rs);
  430. db.close(stat);
  431. db.close(conn);
  432. }
  433. }
  434. public String createMsgId(List<String> list) throws ClassNotFoundException{
  435. long l=(long) ((Math.random()+1)*1000000000);
  436. String msgId=l+"";
  437. if(list.contains(msgId)){
  438. return createMsgId(list);
  439. }
  440. else{
  441. // log.info("msgid==="+msgId);
  442. return msgId;
  443. }
  444. }
  445. }