PublicController.java 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. package com.goafanti.common.controller;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. import java.util.UUID;
  11. import javax.annotation.Resource;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletResponse;
  14. import org.apache.poi.ss.usermodel.Cell;
  15. import org.apache.poi.ss.usermodel.Row;
  16. import org.apache.poi.ss.usermodel.Sheet;
  17. import org.apache.poi.ss.usermodel.Workbook;
  18. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.beans.factory.annotation.Value;
  21. import org.springframework.context.annotation.Scope;
  22. import org.springframework.http.MediaType;
  23. import org.springframework.stereotype.Controller;
  24. import org.springframework.web.bind.annotation.RequestMapping;
  25. import org.springframework.web.bind.annotation.RequestMethod;
  26. import org.springframework.web.bind.annotation.RequestParam;
  27. import org.springframework.web.bind.annotation.ResponseBody;
  28. import org.springframework.web.multipart.MultipartFile;
  29. import com.goafanti.admin.service.AdminService;
  30. import com.goafanti.admin.service.AttachmentService;
  31. import com.goafanti.common.bo.Error;
  32. import com.goafanti.common.bo.Result;
  33. import com.goafanti.common.constant.ErrorConstants;
  34. import com.goafanti.common.enums.UserType;
  35. import com.goafanti.common.model.User;
  36. import com.goafanti.common.service.DistrictGlossoryService;
  37. import com.goafanti.common.service.FieldGlossoryService;
  38. import com.goafanti.common.service.IndustryCategoryService;
  39. import com.goafanti.common.utils.LoggerUtils;
  40. import com.goafanti.common.utils.MobileMessageUtils;
  41. import com.goafanti.common.utils.PasswordUtil;
  42. import com.goafanti.common.utils.PictureUtils;
  43. import com.goafanti.common.utils.StringUtils;
  44. import com.goafanti.common.utils.TimeUtils;
  45. import com.goafanti.common.utils.VerifyCodeUtils;
  46. import com.goafanti.common.utils.Excel.FileUtils;
  47. import com.goafanti.core.shiro.token.TokenManager;
  48. import com.goafanti.user.service.UserService;
  49. @Controller
  50. @Scope(value = "prototype")
  51. @RequestMapping("/open")
  52. public class PublicController extends BaseController {
  53. @Value(value = "${accessKey}")
  54. private String accessKey = null;
  55. @Value(value = "${accessSecret}")
  56. private String accessSecret = null;
  57. @Value(value = "${upload.path}")
  58. private String uploadPath = null;
  59. @Value(value = "${upload.private.path}")
  60. private String uploadPrivatePath = null;
  61. @Value(value = "${static.host}")
  62. private String staticHost = null;
  63. @Value(value = "${mobileCodeTemplate}")
  64. private String mobileCodeTemplate = null;
  65. @Value(value = "${mobileRemindCodeTemplate}")
  66. private String mobileRemindCodeTemplate = null;
  67. @Resource
  68. private UserService userService;
  69. @Resource
  70. private AttachmentService aftFileService;
  71. @Resource
  72. private AdminService adminService;
  73. @Resource
  74. private FieldGlossoryService fieldGlossoryService;
  75. @Autowired
  76. private IndustryCategoryService industryCategoryService;
  77. @Autowired
  78. private DistrictGlossoryService districtGlossoryService;
  79. @Value(value = "${patentTemplate}")
  80. private String patentTemplate = null;
  81. @Resource(name = "passwordUtil")
  82. private PasswordUtil passwordUtil;
  83. /**
  84. * 获取验证码
  85. *
  86. * @param response
  87. */
  88. @RequestMapping(value = "/getVCode", method = RequestMethod.GET)
  89. public void getVCode(HttpServletResponse response, HttpServletRequest request) {
  90. try {
  91. response.setHeader("Pragma", "No-cache");
  92. response.setHeader("Cache-Control", "no-cache");
  93. response.setDateHeader("Expires", 0);
  94. response.setContentType("image/jpg");
  95. // 生成随机字串
  96. String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
  97. // 存入Shiro会话session
  98. TokenManager.setVal2Session(VerifyCodeUtils.V_CODE, verifyCode.toLowerCase());
  99. // 生成图片
  100. int w = 146, h = 33;
  101. VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
  102. } catch (Exception e) {
  103. LoggerUtils.fmtError(getClass(), e, "获取验证码异常:%s", e.getMessage());
  104. }
  105. }
  106. /**
  107. * 手机验证码
  108. *
  109. * @param mobile
  110. * @param sign
  111. * 是否用与找回密码
  112. * @param type
  113. * @return
  114. */
  115. @RequestMapping(value = "/getMCode", method = RequestMethod.GET)
  116. @ResponseBody
  117. public Result getMcode(String mobile, boolean sign, Integer type, String verificationCode) {
  118. Result res = new Result();
  119. // 用于找回密码
  120. if (sign) {
  121. if (null == userService.selectByMobieAndType(mobile.trim(), type)) {
  122. res.getError().add(buildError(ErrorConstants.NON_REGISTER, "", "该用户未注册!"));
  123. return res;
  124. }
  125. }
  126. if (!sign) {
  127. if (StringUtils.isBlank(verificationCode)) {
  128. res.getError().add(buildError(ErrorConstants.VCODE_EMPTY_ERROR, "", "图像验证码不能为空!"));
  129. return res;
  130. }
  131. if (!VerifyCodeUtils.verifyCode(verificationCode)) {
  132. res.getError().add(buildError(ErrorConstants.VCODE_ERROR, "", "图形验证码输入错误!"));
  133. return res;
  134. }
  135. }
  136. if (TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE_TIME) == null
  137. || TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE_TIME) == "") {
  138. sendMessage(mobile, res,VerifyCodeUtils.M_CODE);
  139. } else if (TimeUtils.checkOverTime("getMCode")) {
  140. VerifyCodeUtils.clearMobileCode();
  141. VerifyCodeUtils.clearMobileCodeTime();
  142. sendMessage(mobile, res,VerifyCodeUtils.M_CODE);
  143. } else {
  144. res.getError().add(buildError(ErrorConstants.MCODE_FREQUENCY_ERROR, "", "手机验证码发送频繁!"));
  145. }
  146. return res;
  147. }
  148. /**
  149. *
  150. * @param mobile
  151. * @param res
  152. * @return
  153. */
  154. private Result sendMessage(String mobile, Result res,String codeType) {
  155. String mobileVerifyCode = VerifyCodeUtils.generateMobileVerifyCode(6); // 生成随机字串
  156. if(VerifyCodeUtils.M_CODE.equals(codeType)){
  157. TokenManager.setVal2Session(VerifyCodeUtils.M_CODE, mobileVerifyCode);// 存入Shiro会话session
  158. TokenManager.setVal2Session(VerifyCodeUtils.M_CODE_TIME, System.currentTimeMillis());
  159. }else if(VerifyCodeUtils.RESET_CODE.equals(codeType)){
  160. TokenManager.setVal2Session(VerifyCodeUtils.RESET_CODE, mobileVerifyCode);// 存入Shiro会话session
  161. TokenManager.setVal2Session(VerifyCodeUtils.RESET_CODE_TIME, System.currentTimeMillis());
  162. }
  163. String paramString = "{\"code\":\"" + mobileVerifyCode + "\",\"product\":\"技淘网\"}";
  164. String ret = MobileMessageUtils.sendMessage(mobileCodeTemplate, paramString, mobile, accessKey, accessSecret);
  165. if (StringUtils.isNotBlank(ret)) {
  166. res.getError().add(buildError(ErrorConstants.M_CODE_ERROR));
  167. }
  168. return res;
  169. }
  170. /**
  171. * 下载图片
  172. *
  173. * @param response
  174. * @param path
  175. * @param request
  176. */
  177. @RequestMapping(value = "/downLoadPicture", method = RequestMethod.GET)
  178. public Result downLoadPicture(HttpServletResponse response, String path, HttpServletRequest request) {
  179. Result res = new Result();
  180. if (StringUtils.isBlank(path)) {
  181. res.getError().add(buildError(ErrorConstants.FILE_NON_EXISTENT));
  182. return res;
  183. }
  184. String filename = Long.toString(System.nanoTime()) + ".jpg";
  185. InputStream in = null;
  186. OutputStream out = null;
  187. byte[] buffer = new byte[8 * 1024];
  188. String fileSaveRootPath = "";
  189. try {
  190. fileSaveRootPath = uploadPrivatePath + path;
  191. File file = new File(fileSaveRootPath);
  192. in = new FileInputStream(file);
  193. out = response.getOutputStream();
  194. // 设置文件MIME类型
  195. response.setContentType("application/octet-stream");
  196. response.setHeader("Content-Disposition", "attachment; filename=" + filename);
  197. for (;;) {
  198. int bytes = in.read(buffer);
  199. if (bytes == -1) {
  200. break;
  201. }
  202. out.write(buffer, 0, bytes);
  203. }
  204. } catch (IOException e) {
  205. LoggerUtils.fmtError(getClass(), e, "IO错误:%s", e.getMessage());
  206. } finally {
  207. try {
  208. if (null != in) {
  209. in.close();
  210. }
  211. } catch (IOException e) {
  212. LoggerUtils.fmtError(getClass(), e, "IO错误:%s", e.getMessage());
  213. }
  214. try {
  215. if (null != out) {
  216. out.close();
  217. }
  218. } catch (IOException e) {
  219. LoggerUtils.fmtError(getClass(), e, "IO错误:%s", e.getMessage());
  220. }
  221. }
  222. return res;
  223. }
  224. /**
  225. * 删除图片文件(public图片)
  226. *
  227. * @param path
  228. * @return
  229. */
  230. @RequestMapping(value = "/deleteUploadPicture", method = RequestMethod.POST)
  231. public boolean deleteUploadPicture(String path) {
  232. boolean flag = false;
  233. path = uploadPath + path;
  234. File file = new File(path);
  235. // 判断目录或文件是否存在
  236. if (!file.exists() || !file.isFile()) { // 不存在返回 false
  237. return flag;
  238. } else {
  239. return file.delete();
  240. }
  241. }
  242. /**
  243. * 获取并输出private图片
  244. */
  245. @RequestMapping(value = "/writeImage", method = RequestMethod.GET)
  246. public void writeImage(HttpServletResponse response, HttpServletRequest request, String path) {
  247. try {
  248. String realPath = uploadPrivatePath + path;
  249. PictureUtils.outputImage(response, realPath);
  250. } catch (IOException e) {
  251. LoggerUtils.fmtError(getClass(), e, "获取图片异常:%s", e.getMessage());
  252. }
  253. }
  254. /**
  255. * 下载文件
  256. *
  257. * @param res
  258. * @param fileName
  259. * @param response
  260. * @param path
  261. * @param request
  262. * @return
  263. */
  264. @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
  265. public Result downloadFile(String fileName, HttpServletResponse response, String path) {
  266. Result res = new Result();
  267. return handleDownloadFile(response, fileName, path, res);
  268. }
  269. /**
  270. * 下载模版文件
  271. *
  272. * @param response
  273. * @return
  274. */
  275. @RequestMapping(value = "/downloadTemplateFile", method = RequestMethod.GET)
  276. public Result downloadTemplateFile(HttpServletResponse response, String sign) {
  277. Result res = new Result();
  278. String fileName = "";
  279. String path = aftFileService.selectAftFileBySign(sign).getFilePath();
  280. String suffix = path.substring(path.lastIndexOf("."));
  281. if (sign.equals("patent_prory_statement")) {
  282. fileName = "专利代理委托书模版" + suffix;
  283. } else {
  284. fileName = System.nanoTime() + " ";
  285. }
  286. if (!StringUtils.isBlank(path)) {
  287. return handleDownloadFile(response, fileName, path, res);
  288. } else {
  289. res.getError().add(buildError(ErrorConstants.FILE_NON_EXISTENT, "", "下载文件不存在!"));
  290. return res;
  291. }
  292. }
  293. private Result handleDownloadFile(HttpServletResponse response, String fileName, String path, Result res) {
  294. String fileSaveRootPath = uploadPrivatePath + path;
  295. InputStream in = null;
  296. OutputStream out = null;
  297. byte[] buffer = new byte[8 * 1024];
  298. try {
  299. File file = new File(fileSaveRootPath);
  300. in = new FileInputStream(file);
  301. out = response.getOutputStream();
  302. response.setContentType("multipart/form-data");
  303. fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
  304. response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
  305. for (;;) {
  306. int bytes = in.read(buffer);
  307. if (bytes == -1) {
  308. break;
  309. }
  310. out.write(buffer, 0, bytes);
  311. }
  312. } catch (IOException e) {
  313. LoggerUtils.fmtError(getClass(), e, "IO错误:%s", e.getMessage());
  314. } finally {
  315. try {
  316. in.close();
  317. } catch (IOException e) {
  318. LoggerUtils.fmtError(getClass(), e, "IO错误:%s", e.getMessage());
  319. }
  320. try {
  321. out.close();
  322. } catch (IOException e) {
  323. LoggerUtils.fmtError(getClass(), e, "IO错误:%s", e.getMessage());
  324. }
  325. }
  326. return res;
  327. }
  328. @RequestMapping(value = "/findIndustryCategory", method = RequestMethod.GET)
  329. @ResponseBody
  330. public Result findIndustryCategory(String id, String noCache) {
  331. Integer pid = 0;
  332. if (StringUtils.isNumeric(id)) {
  333. try {
  334. pid = Integer.parseInt(id);
  335. } catch (Exception e) {
  336. pid = 0;
  337. }
  338. }
  339. if (StringUtils.isNotBlank(noCache)) {
  340. industryCategoryService.clear(pid);
  341. }
  342. return new Result().data(industryCategoryService.list(pid));
  343. }
  344. @RequestMapping(value = "/findDistrict", method = RequestMethod.GET)
  345. @ResponseBody
  346. public Result findDistrictGlossory(String id, String noCache) {
  347. Integer pid = 0;
  348. if (StringUtils.isNumeric(id)) {
  349. try {
  350. pid = Integer.parseInt(id);
  351. } catch (Exception e) {
  352. pid = 0;
  353. }
  354. }
  355. if (StringUtils.isNotBlank(noCache)) {
  356. districtGlossoryService.clear(pid);
  357. }
  358. return new Result().data(districtGlossoryService.list(pid));
  359. }
  360. /**
  361. *
  362. * @param mobileCode
  363. * @return
  364. */
  365. @RequestMapping(value = "/checkMCode", method = RequestMethod.POST)
  366. @ResponseBody
  367. public Result checkMCode(String mobileCode) {
  368. Result res = new Result();
  369. if (StringUtils.isBlank(mobileCode)) {
  370. res.getError().add(buildError(ErrorConstants.MCODE_EMPTY_ERROR, "", "手机验证码"));
  371. return res;
  372. }
  373. if (TimeUtils.checkOverTime(VerifyCodeUtils.M_CODE)) {
  374. res.getError().add(buildError(ErrorConstants.MCODE_OVERTIME_ERROR, "", "手机验证码超时失效!"));
  375. VerifyCodeUtils.clearMobileCode();
  376. VerifyCodeUtils.clearMobileCodeTime();
  377. return res;
  378. }
  379. if (!TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE).equals(mobileCode)) {
  380. res.getError().add(buildError(ErrorConstants.MCODE_ERROR, "", "手机验证码错误"));
  381. return res;
  382. }
  383. // resetCode
  384. if (res.getError().isEmpty()) {
  385. String resetCode = UUID.randomUUID().toString();
  386. TokenManager.setVal2Session(VerifyCodeUtils.RESET_CODE, resetCode);
  387. TokenManager.setVal2Session(VerifyCodeUtils.RESET_CODE_TIME, System.currentTimeMillis());
  388. res.setData(resetCode);
  389. }
  390. return res;
  391. }
  392. /**
  393. * 重置密码
  394. *
  395. * @param resetCode
  396. * @param mobile
  397. * @param type
  398. * @param newPwd
  399. * @return
  400. */
  401. @RequestMapping(value = "/resetPwd", method = RequestMethod.POST)
  402. @ResponseBody
  403. public Result resetPwd(String resetCode, String mobile, Integer type, String newPwd) {
  404. Result res = new Result();
  405. if (TimeUtils.checkOverTime(VerifyCodeUtils.M_CODE)) {
  406. res.getError().add(buildError(ErrorConstants.RESET_CODE_OVERTIME, "", "页面超时失效,请重新获取验证码!"));
  407. cleanCodeSession();
  408. return res;
  409. }
  410. if(null == TokenManager.getSession().getAttribute(VerifyCodeUtils.RESET_CODE)){
  411. res.getError().add(buildError(ErrorConstants.RESET_CODE_OVERTIME, "", "页面超时失效,请重新获取验证码!"));
  412. cleanCodeSession();
  413. return res;
  414. }else if(!TokenManager.getSession().getAttribute(VerifyCodeUtils.RESET_CODE).equals(resetCode)){
  415. res.getError().add(buildError(ErrorConstants.RESET_CODE_ERROR, "", "验证码错误,请重新获取验证码!"));
  416. cleanCodeSession();
  417. return res;
  418. }
  419. if (StringUtils.isBlank(newPwd)) {
  420. res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "新密码"));
  421. return res;
  422. }
  423. if (StringUtils.isBlank(mobile)) {
  424. res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "mobile"));
  425. return res;
  426. }
  427. if (!UserType.ORGANIZATION.getCode().equals(type) && !UserType.PERSONAL.getCode().equals(type)) {
  428. res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "type"));
  429. return res;
  430. }
  431. User user = userService.selectByMobieAndType(mobile, type);
  432. if (null == user) {
  433. res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "mobile"));
  434. return res;
  435. }
  436. user.setPassword(newPwd);
  437. user.setPassword(passwordUtil.getEncryptPwd(user));
  438. userService.updateByPrimaryKeySelective(user);
  439. VerifyCodeUtils.clearResetCode();
  440. VerifyCodeUtils.clearResetCodeTime();
  441. return res;
  442. }
  443. private void cleanCodeSession() {
  444. VerifyCodeUtils.clearResetCode();
  445. VerifyCodeUtils.clearResetCodeTime();
  446. VerifyCodeUtils.clearMobileCode();
  447. VerifyCodeUtils.clearMobileCodeTime();
  448. }
  449. @RequestMapping(value = "/getRegisterMCode", method = RequestMethod.GET )
  450. @ResponseBody
  451. public Result getRegisterMCode(String mobile){
  452. Result res = new Result();
  453. if (TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE_TIME) == null
  454. || TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE_TIME) == "") {
  455. sendMessage(mobile, res,VerifyCodeUtils.M_CODE);
  456. } else if (TimeUtils.checkOverTime("getMCode")) {
  457. VerifyCodeUtils.clearMobileCode();
  458. VerifyCodeUtils.clearMobileCodeTime();
  459. sendMessage(mobile, res,VerifyCodeUtils.M_CODE);
  460. } else {
  461. res.getError().add(buildError(ErrorConstants.MCODE_FREQUENCY_ERROR, "", "手机验证码发送频繁!"));
  462. }
  463. return res;
  464. }
  465. @RequestMapping(value = "/getResetMCode", method = RequestMethod.GET )
  466. @ResponseBody
  467. public Result getResetMCode(String mobile, Integer type) {
  468. Result res = new Result();
  469. if (null == userService.selectByMobieAndType(mobile.trim(), type)) {
  470. res.getError().add(buildError(ErrorConstants.NON_REGISTER, "", "该用户未注册!"));
  471. return res;
  472. }
  473. if (TokenManager.getSession().getAttribute(VerifyCodeUtils.RESET_CODE_TIME) == null
  474. || TokenManager.getSession().getAttribute(VerifyCodeUtils.RESET_CODE_TIME) == "") {
  475. sendMessage(mobile, res,VerifyCodeUtils.RESET_CODE);
  476. } else if (TimeUtils.checkOverTime("resetCode")) {
  477. VerifyCodeUtils.clearMobileCode();
  478. VerifyCodeUtils.clearMobileCodeTime();
  479. sendMessage(mobile, res,VerifyCodeUtils.RESET_CODE);
  480. } else {
  481. res.getError().add(buildError(ErrorConstants.MCODE_FREQUENCY_ERROR, "", "手机验证码发送频繁!"));
  482. }
  483. return res;
  484. }
  485. /** 省市区查询 **/
  486. @RequestMapping(value = "/listAllProvince" , method = RequestMethod.POST)
  487. @ResponseBody
  488. public Result listAllProvince(){
  489. Result res = new Result();
  490. res.setData(districtGlossoryService.getProvince());
  491. return res;
  492. }
  493. @RequestMapping(value = "/listDefaultPassword" , method = RequestMethod.GET)
  494. @ResponseBody
  495. public Result listDefaultPassword(String depId){
  496. Result res=new Result();
  497. res.setData(adminService.getListDefaultPassword(depId));
  498. return res;
  499. }
  500. /**
  501. * 导入流水
  502. * @param file
  503. * @param request
  504. * @return
  505. */
  506. @SuppressWarnings("unchecked")
  507. @RequestMapping(value = "/import" , method = RequestMethod.POST)
  508. @ResponseBody
  509. public Result importTeacher(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
  510. Result res=new Result();
  511. String fileName = file.getOriginalFilename();
  512. if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
  513. res.error(new Error("", "格式不正确"));
  514. }
  515. //检查文件
  516. try {
  517. checkFile(file);
  518. } catch (IOException e) {
  519. e.printStackTrace();
  520. }
  521. //获得Workbook工作薄对象
  522. Workbook workbook = getWorkBook(file);
  523. //创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
  524. List<List<String>> list = new ArrayList<>();
  525. if(workbook != null){
  526. for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
  527. //获得当前sheet工作表
  528. Sheet sheet = workbook.getSheetAt(sheetNum);
  529. if(sheet == null){
  530. continue;
  531. }
  532. //获得当前sheet的开始行
  533. int firstRowNum = sheet.getFirstRowNum();
  534. //获得当前sheet的结束行
  535. int lastRowNum = sheet.getLastRowNum();
  536. //循环除了第2行的所有行
  537. for(int rowNum = firstRowNum+2;rowNum <= lastRowNum;rowNum++){
  538. //获得当前行
  539. Row row = sheet.getRow(rowNum);
  540. if(row == null){
  541. continue;
  542. }
  543. //获得当前行的开始列
  544. int firstCellNum = row.getFirstCellNum();
  545. //获得当前行的列数
  546. int lastCellNum = row.getLastCellNum();
  547. @SuppressWarnings("rawtypes")
  548. ArrayList arrayList = new ArrayList();
  549. //循环当前行 cellNum = (firstCellNum+1) 则是除开第一例
  550. for(int cellNum = (firstCellNum); cellNum < lastCellNum;cellNum++){
  551. Cell cell = row.getCell(cellNum);
  552. arrayList.add(getCellValue(cell));
  553. }
  554. list.add(arrayList);
  555. }
  556. }
  557. }
  558. System.out.println(list.toString());
  559. return res;
  560. }
  561. public static void checkFile(MultipartFile file) throws IOException{
  562. //判断文件是否存在
  563. if(null == file){
  564. throw new FileNotFoundException("文件不存在!");
  565. }
  566. //获得文件名
  567. String fileName = file.getOriginalFilename();
  568. //判断文件是否是excel文件
  569. if(!fileName.endsWith("xls") && !fileName.endsWith("xlsx")){
  570. throw new IOException(fileName + "不是excel文件");
  571. }
  572. }
  573. public static Workbook getWorkBook(MultipartFile file) {
  574. //创建Workbook工作薄对象,表示整个excel
  575. Workbook workbook = null;
  576. try {
  577. //获取excel文件的io流
  578. InputStream is = file.getInputStream();
  579. //如果是xls,使用HSSFWorkbook;如果是xlsx,使用XSSFWorkbook
  580. workbook = new XSSFWorkbook(is);
  581. } catch (IOException e) {
  582. }
  583. return workbook;
  584. }
  585. @SuppressWarnings("deprecation")
  586. public static String getCellValue(Cell cell){
  587. String cellValue = "";
  588. if(cell == null){
  589. return cellValue;
  590. }
  591. //把数字当成String来读,避免出现1读成1.0的情况
  592. if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
  593. cell.setCellType(Cell.CELL_TYPE_STRING);
  594. }
  595. //判断数据的类型
  596. switch (cell.getCellType()){
  597. case Cell.CELL_TYPE_NUMERIC: //数字
  598. cellValue = String.valueOf(cell.getNumericCellValue());
  599. break;
  600. case Cell.CELL_TYPE_STRING: //字符串
  601. cellValue = String.valueOf(cell.getStringCellValue());
  602. break;
  603. case Cell.CELL_TYPE_BOOLEAN: //Boolean
  604. cellValue = String.valueOf(cell.getBooleanCellValue());
  605. break;
  606. case Cell.CELL_TYPE_FORMULA: //公式
  607. cellValue = String.valueOf(cell.getCellFormula());
  608. break;
  609. case Cell.CELL_TYPE_BLANK: //空值
  610. cellValue = "未知";
  611. break;
  612. case Cell.CELL_TYPE_ERROR: //故障
  613. cellValue = "非法字符";
  614. break;
  615. default:
  616. cellValue = "未知类型";
  617. break;
  618. }
  619. return cellValue;
  620. }
  621. /**
  622. * 通用下载请求
  623. *
  624. * @param fileName 文件名称
  625. * @param delete 是否删除
  626. */
  627. @RequestMapping("/download")
  628. public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
  629. {
  630. try
  631. {
  632. if (!FileUtils.checkAllowDownload(fileName))
  633. {
  634. throw new Exception("文件名称({})非法,不允许下载。 ");
  635. }
  636. String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
  637. String filePath = uploadPath + fileName;
  638. response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
  639. FileUtils.setAttachmentResponseHeader(response, realFileName);
  640. FileUtils.writeBytes(filePath, response.getOutputStream());
  641. if (delete)
  642. {
  643. FileUtils.deleteFile(filePath);
  644. }
  645. }
  646. catch (Exception e)
  647. {
  648. LoggerUtils.error(PublicController.class,"下载文件失败", e);
  649. }
  650. }
  651. }