TTrainingController.java 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. package com.ruoyi.project.training.controller;
  2. import java.io.*;
  3. import java.net.URLEncoder;
  4. import java.text.SimpleDateFormat;
  5. import java.util.*;
  6. import com.alibaba.fastjson.JSON;
  7. import com.ruoyi.common.utils.DateUtils;
  8. import com.ruoyi.common.utils.DictUtils;
  9. import com.ruoyi.common.utils.file.ExcelUtils;
  10. import com.ruoyi.common.utils.file.FileUploadUtils;
  11. import com.ruoyi.common.utils.poi.CustomXWPFDocument;
  12. import com.ruoyi.framework.config.RuoYiConfig;
  13. import com.ruoyi.project.plant.domain.TStaffmgr;
  14. import com.ruoyi.project.plant.mapper.TStaffmgrMapper;
  15. import com.ruoyi.project.plant.service.ITStaffmgrService;
  16. import com.ruoyi.project.system.domain.SysDept;
  17. import com.ruoyi.project.system.domain.SysDictData;
  18. import com.ruoyi.project.system.service.ISysDeptService;
  19. import com.ruoyi.project.system.service.ISysDictTypeService;
  20. import com.ruoyi.project.training.domain.TTrainingDevice;
  21. import com.ruoyi.project.training.domain.TTrainingNon;
  22. import com.ruoyi.project.training.domain.TTrainingRegular;
  23. import com.ruoyi.project.training.mapper.TTrainingMapper;
  24. import com.ruoyi.project.training.service.ITTrainingDeviceService;
  25. import com.ruoyi.project.training.service.ITTrainingNonService;
  26. import com.ruoyi.project.training.service.ITTrainingRegularService;
  27. import org.apache.commons.lang3.StringUtils;
  28. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  29. import org.apache.poi.ss.usermodel.*;
  30. import org.apache.poi.ss.util.CellRangeAddress;
  31. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  32. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  33. import org.apache.poi.xwpf.usermodel.*;
  34. import org.springframework.security.access.prepost.PreAuthorize;
  35. import org.springframework.beans.factory.annotation.Autowired;
  36. import org.springframework.web.bind.annotation.*;
  37. import com.ruoyi.framework.aspectj.lang.annotation.Log;
  38. import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
  39. import com.ruoyi.project.training.domain.TTraining;
  40. import com.ruoyi.project.training.service.ITTrainingService;
  41. import com.ruoyi.framework.web.controller.BaseController;
  42. import com.ruoyi.framework.web.domain.AjaxResult;
  43. import com.ruoyi.common.utils.poi.ExcelUtil;
  44. import com.ruoyi.framework.web.page.TableDataInfo;
  45. import org.springframework.web.multipart.MultipartFile;
  46. import javax.annotation.Resource;
  47. import javax.servlet.http.HttpServletRequest;
  48. import javax.servlet.http.HttpServletResponse;
  49. /**
  50. * 培训计划Controller
  51. *
  52. * @author ruoyi
  53. * @date 2020-12-02
  54. */
  55. @RestController
  56. @RequestMapping("/training/training")
  57. public class TTrainingController extends BaseController {
  58. @Autowired
  59. private ITTrainingService tTrainingService;
  60. @Autowired
  61. private ITTrainingRegularService tTrainingRegularService;
  62. @Autowired
  63. private ISysDeptService iSysDeptService;
  64. @Autowired
  65. private ISysDictTypeService iSysDictTypeService;
  66. @Autowired
  67. private ITTrainingNonService tTrainingNonService;
  68. @Resource
  69. private TTrainingMapper tTrainingMapper;
  70. @Resource
  71. private TStaffmgrMapper tStaffmgrMapper;
  72. @Autowired
  73. private ITStaffmgrService tStaffmgrService;
  74. @Autowired
  75. private ITTrainingDeviceService tTrainingDeviceService;
  76. /**
  77. * 查询培训计划列表
  78. */
  79. @PreAuthorize("@ss.hasPermi('training:training:list')")
  80. @GetMapping("/list")
  81. public TableDataInfo list(TTraining tTraining) {
  82. startPage();
  83. List<TTraining> list = tTrainingService.selectTTrainingList(tTraining);
  84. logger.info("====1111111::::::" + list.size());
  85. for (TTraining t : list) {
  86. int mustTraining = 0;
  87. if (t.getDesignatedStaff() != null) {
  88. String[] designatedStaff = t.getDesignatedStaff().split(",");
  89. mustTraining = designatedStaff.length;
  90. }
  91. t.setMustTraining(t.getPositionNum() + mustTraining);
  92. TTrainingNon tTrainingNon = new TTrainingNon();
  93. tTrainingNon.setTrainingId(t.getId());
  94. List<TTrainingNon> tTrainingNons = tTrainingNonService.selectTTrainingNonList(tTrainingNon);
  95. int i = 0;
  96. for (TTrainingNon n : tTrainingNons) {
  97. if (n.getTrainingDate() == null && n.getTrainingStaff() == null) {
  98. i++;
  99. logger.info("nons:" + n);
  100. }
  101. }
  102. t.setHaveTraining(t.getPositionNum() + mustTraining - i);
  103. }
  104. return getDataTable(list);
  105. }
  106. /**
  107. * 导出培训计划列表
  108. */
  109. @PreAuthorize("@ss.hasPermi('training:training:export')")
  110. @Log(title = "培训计划", businessType = BusinessType.EXPORT)
  111. @GetMapping("/export")
  112. public AjaxResult export(TTraining tTraining) {
  113. List<TTraining> list = tTrainingService.selectTTrainingList(tTraining);
  114. ExcelUtil<TTraining> util = new ExcelUtil<TTraining>(TTraining.class);
  115. return util.exportExcel(list, "training");
  116. }
  117. /**
  118. * 获取培训计划详细信息
  119. */
  120. @PreAuthorize("@ss.hasPermi('training:training:query')")
  121. @GetMapping(value = "/{id}")
  122. public AjaxResult getInfo(@PathVariable("id") Long id) {
  123. return AjaxResult.success(tTrainingService.selectTTrainingById(id));
  124. }
  125. /**
  126. * 新增培训计划
  127. */
  128. @PreAuthorize("@ss.hasPermi('training:training:add')")
  129. @Log(title = "培训计划", businessType = BusinessType.INSERT)
  130. @PostMapping
  131. public AjaxResult add(@RequestBody TTraining tTraining) {
  132. tTraining.setCreaterCode(getUserId().toString());
  133. int doInsert = tTrainingService.insertTTraining(tTraining);
  134. //培训岗位人员
  135. if (tTraining.getPosition() != null) {
  136. TStaffmgr s = new TStaffmgr();
  137. s.setActualposts(tTraining.getPosition());
  138. List<TStaffmgr> trainingStaff = tStaffmgrService.selectAllTStaffmgrList(s);
  139. try {
  140. //判断离职
  141. if (!org.apache.commons.lang.StringUtils.isEmpty(tTraining.getYear())) {
  142. Iterator<TStaffmgr> iterator = trainingStaff.iterator();
  143. while (iterator.hasNext()) {
  144. TStaffmgr t = iterator.next();
  145. if (t.getLeftDate() != null && t.getDelFlag() == 9) {
  146. if (t.getLeftDate().getTime() - tTraining.getStartDate().getTime() < 0l) {
  147. logger.debug(t.getName() + "离职时间小于培训时间");
  148. iterator.remove();
  149. }
  150. }
  151. }
  152. }
  153. } catch (Exception e) {
  154. logger.error(e.toString());
  155. }
  156. for (TStaffmgr staff : trainingStaff) {
  157. TTrainingDevice tTrainingDevice = new TTrainingDevice();
  158. tTrainingDevice.setStaffId(staff.getStaffid());
  159. tTrainingDevice.setRegularId(tTraining.getId());
  160. tTrainingDevice.setStartDate(tTraining.getCourseStartdate());
  161. tTrainingDevice.setSupplementary("0");
  162. tTrainingDeviceService.insertTTrainingDevice(tTrainingDevice);
  163. }
  164. }
  165. if (tTraining.getDesignatedStaff() != null) {
  166. String[] designated = tTraining.getDesignatedStaff().split(",");
  167. for (String staffid : designated) {
  168. TStaffmgr staffmgr = tStaffmgrService.selectTStaffmgrByStaffId(staffid);
  169. TTrainingDevice tTrainingDevice = new TTrainingDevice();
  170. tTrainingDevice.setStaffId(staffmgr.getStaffid());
  171. tTrainingDevice.setRegularId(tTraining.getId());
  172. tTrainingDevice.setStartDate(tTraining.getCourseStartdate());
  173. tTrainingDevice.setSupplementary("0");
  174. tTrainingDeviceService.insertTTrainingDevice(tTrainingDevice);
  175. }
  176. }
  177. return toAjax(doInsert);
  178. }
  179. /**
  180. * 修改培训计划
  181. */
  182. @PreAuthorize("@ss.hasPermi('training:training:edit')")
  183. @Log(title = "培训计划", businessType = BusinessType.UPDATE)
  184. @PutMapping
  185. public AjaxResult edit(@RequestBody TTraining tTraining) {
  186. tTraining.setUpdaterCode(getUserId().toString());
  187. tTraining.setUpdatedate(new Date());
  188. //查找跟这条培训计划相关联的装置级培训记录 修改其培训的年份,课程名称和课程代码
  189. //如果是定期类 就修改下培训计划里面的内容
  190. if (tTraining.getTrainingType().equals("10")) {
  191. if (tTraining.getRegularId() == null) {
  192. logger.info("没有对应培训计划");
  193. } else {
  194. TTrainingRegular t = tTrainingRegularService.selectTTrainingRegularById(tTraining.getRegularId());
  195. t.setItem(tTraining.getCourse());
  196. t.setCourseCode(tTraining.getCourseid());
  197. t.setYear(tTraining.getYear());
  198. t.setDelFlag(tTraining.getDelFlag());
  199. int result = tTrainingRegularService.updateTTrainingRegular(t);
  200. }
  201. }
  202. TTraining oldTraining = tTrainingService.selectTTrainingById(tTraining.getId());
  203. int i = 0;
  204. if (oldTraining.getPosition() != null) {
  205. if (!oldTraining.getPosition().equals(tTraining.getPosition())) {
  206. i = 1;
  207. }
  208. } else {
  209. if (tTraining.getPosition() != null) {
  210. i = 1;
  211. }
  212. }
  213. if (oldTraining.getDesignatedStaff() != null) {
  214. if (!oldTraining.getDesignatedStaff().equals(tTraining.getDesignatedStaff())) {
  215. i = 1;
  216. }
  217. } else {
  218. if (tTraining.getDesignatedStaff() != null) {
  219. i = 1;
  220. }
  221. }
  222. if (tTraining.getCourseStartdate() != null) {
  223. logger.info("修改了时间");
  224. i = 1;
  225. }
  226. if (i == 1) {
  227. logger.info("修改了需参培人员名单");
  228. //如果存在条目
  229. if (oldTraining.getPosition() != null || oldTraining.getDesignatedStaff() != null) {
  230. TTrainingDevice tTrainingDevice = new TTrainingDevice();
  231. tTrainingDevice.setRegularId(tTraining.getId());
  232. tTrainingDeviceService.deleteTTrainingDevice(tTrainingDevice);
  233. }
  234. //参培岗位人员
  235. if (tTraining.getPosition() != null) {
  236. TStaffmgr s = new TStaffmgr();
  237. s.setActualposts(tTraining.getPosition());
  238. List<TStaffmgr> trainingStaff = tStaffmgrService.selectAllTStaffmgrList(s);
  239. try {
  240. //判断离职
  241. if (!org.apache.commons.lang.StringUtils.isEmpty(tTraining.getYear())) {
  242. Iterator<TStaffmgr> iterator = trainingStaff.iterator();
  243. while (iterator.hasNext()) {
  244. TStaffmgr t = iterator.next();
  245. if (t.getLeftDate() != null && t.getDelFlag() == 9) {
  246. if (t.getLeftDate().getTime() - tTraining.getStartDate().getTime() < 0l) {
  247. logger.debug(t.getName() + "离职时间小于培训时间");
  248. iterator.remove();
  249. }
  250. }
  251. }
  252. }
  253. } catch (Exception e) {
  254. logger.error(e.toString());
  255. }
  256. for (TStaffmgr staff : trainingStaff) {
  257. TTrainingDevice tTrainingDevice = new TTrainingDevice();
  258. tTrainingDevice.setStaffId(staff.getStaffid());
  259. tTrainingDevice.setRegularId(tTraining.getId());
  260. tTrainingDevice.setStartDate(tTraining.getCourseStartdate());
  261. tTrainingDevice.setSupplementary("0");
  262. tTrainingDeviceService.insertTTrainingDevice(tTrainingDevice);
  263. }
  264. }
  265. if (tTraining.getDesignatedStaff() != null) {
  266. String[] designated = tTraining.getDesignatedStaff().split(",");
  267. for (String staffid : designated) {
  268. TStaffmgr staffmgr = tStaffmgrService.selectTStaffmgrByStaffId(staffid);
  269. TTrainingDevice tTrainingDevice = new TTrainingDevice();
  270. tTrainingDevice.setStaffId(staffmgr.getStaffid());
  271. tTrainingDevice.setRegularId(tTraining.getId());
  272. tTrainingDevice.setStartDate(tTraining.getCourseStartdate());
  273. tTrainingDevice.setSupplementary("0");
  274. tTrainingDeviceService.insertTTrainingDevice(tTrainingDevice);
  275. }
  276. }
  277. }
  278. return toAjax(tTrainingService.updateTTraining(tTraining));
  279. }
  280. /**
  281. * 删除培训计划
  282. */
  283. @PreAuthorize("@ss.hasPermi('training:training:remove')")
  284. @Log(title = "培训计划", businessType = BusinessType.DELETE)
  285. @DeleteMapping("/{ids}")
  286. public AjaxResult remove(@PathVariable Long[] ids) {
  287. for (Long id : ids) {
  288. TTraining training = tTrainingService.selectTTrainingById(id);
  289. if (training.getPosition() != null || training.getDesignatedStaff() != null) {
  290. TTrainingDevice tTrainingDevice = new TTrainingDevice();
  291. tTrainingDevice.setRegularId(id);
  292. tTrainingDeviceService.deleteTTrainingDevice(tTrainingDevice);
  293. }
  294. }
  295. return toAjax(tTrainingService.deleteTTrainingByIds(ids));
  296. }
  297. /**
  298. * 装置程序清单附件上传
  299. */
  300. @Log(title = "培训计划图片上传", businessType = BusinessType.UPDATE)
  301. @PostMapping("/uploadFile")
  302. public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
  303. if (!file.isEmpty()) {
  304. String avatar = FileUploadUtils.upload(RuoYiConfig.getFilePath("/trainingMOC"), file);
  305. return AjaxResult.success(avatar);
  306. }
  307. return AjaxResult.error("上传图片异常,请联系管理员");
  308. }
  309. /**
  310. * 批量导入培训成绩
  311. */
  312. @PreAuthorize("@ss.hasPermi('training:trainingrecords:add')")
  313. @Log(title = "培训成绩", businessType = BusinessType.INSERT)
  314. @PostMapping("/importData")
  315. public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException {
  316. //获取操作人员ID
  317. Long userId = getUserId();
  318. //报错行数统计
  319. List<Integer> failRow = new ArrayList<Integer>();
  320. Workbook workbook = ExcelUtils.getWorkBook(file);
  321. Sheet sheet = workbook.getSheetAt(0);
  322. List<TTraining> list = new ArrayList<TTraining>();
  323. //字典查询
  324. List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
  325. List<SysDictData> training = iSysDictTypeService.selectDictDataByType("ACTUALPOST");
  326. List<SysDictData> yesno = iSysDictTypeService.selectDictDataByType("YES_NO_EN");
  327. List<SysDictData> staffUnit = iSysDictTypeService.selectDictDataByType("STAFF_UNIT");
  328. List<SysDictData> trainingType = iSysDictTypeService.selectDictDataByType("TRAINING_TYPE");
  329. //部门查询
  330. List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
  331. int rowNum = sheet.getPhysicalNumberOfRows();
  332. int failNumber = 0;
  333. for (int i = 1; i < rowNum; i++) {
  334. try {
  335. logger.info("读取行数:" + i);
  336. Row row = sheet.getRow(i);
  337. int cellNum = row.getPhysicalNumberOfCells();
  338. TTraining entity = new TTraining();
  339. for (int j = 0; j < cellNum; j++) {
  340. Cell cell = row.getCell(j);
  341. // cell.setCellType(CellType.STRING);
  342. String cellValue = ExcelUtils.getCellValue(cell);
  343. logger.info("cellValue:" + cellValue);
  344. if (j == 0) {
  345. if (cellValue != "") {
  346. entity.setYear(cellValue);//年份
  347. }
  348. } else if (j == 1) {
  349. entity.setCourse(cellValue);//培训课程
  350. } else if (j == 2) {
  351. for (SysDictData p : trainingType) {
  352. if (p.getDictLabel().equals(cellValue)) {
  353. entity.setTrainingType(p.getDictValue());
  354. }
  355. }//培训类型
  356. } else if (j == 3) {
  357. entity.setContent(cellValue);//培训内容
  358. } else if (j == 4) {
  359. entity.setCourseid(cellValue);//课程代码
  360. } else if (j == 5) {
  361. entity.setPeriod(cellValue);//培训周期
  362. } else if (j == 6) {
  363. if (cellValue != "") {
  364. entity.setDuration(cellValue);//课时
  365. }
  366. } else if (j == 7) {
  367. entity.setTrainer(cellValue);//培训人
  368. } else if (j == 8) {
  369. String[] units = cellValue.split(",");
  370. String unit = "";
  371. for (int num = 0; num < units.length; num++) {
  372. for (SysDictData p : staffUnit) {
  373. if (p.getDictLabel().equals(units[num].trim())) {
  374. if (num == 0) {
  375. unit = p.getDictValue();
  376. } else {
  377. unit = unit + "," + p.getDictValue();
  378. }
  379. }
  380. entity.setUnit(unit);//培训部门
  381. }
  382. }
  383. } else if (j == 9) {
  384. String[] positionName = cellValue.split(",");
  385. String position = null;
  386. for (int num = 0; num < positionName.length; num++) {
  387. for (SysDictData p : training) {
  388. if (p.getDictLabel().equals(positionName[num].trim())) {
  389. if (num == 0) {
  390. position = p.getDictValue();
  391. } else {
  392. position = position + "," + p.getDictValue();
  393. }
  394. }
  395. entity.setPosition(position);//培训岗位
  396. }
  397. }
  398. } else if (j == 10) {
  399. if (cellValue.length() > 3) {
  400. entity.setCourseStartdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//培训开始日期
  401. }
  402. } else if (j == 11) {
  403. if (cellValue.length() > 3) {
  404. entity.setCourseEnddate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//培训结束日期
  405. }
  406. } else if (j == 12) {
  407. for (SysDictData p : yesno) {
  408. if (p.getDictLabel().equals(cellValue)) {
  409. entity.setIsfinish(Long.parseLong(p.getDictValue()));//是否完成
  410. }
  411. }
  412. } else if (j == 13) {
  413. for (SysDept d : dept) {
  414. if (d.getDeptName().equals(cellValue)) {
  415. entity.setDeptId(d.getDeptId());//部门编号
  416. }
  417. }
  418. } else if (j == 14) {
  419. entity.setRemarks(cellValue);//备注
  420. }
  421. }
  422. entity.setCreaterCode(userId.toString());
  423. logger.info("entity:" + entity);
  424. list.add(entity);
  425. } catch (Exception e) {
  426. failNumber++;
  427. failRow.add(i + 1);
  428. }
  429. }
  430. int successNumber = 0;
  431. int failNum = 0;
  432. for (TTraining t : list
  433. ) {
  434. failNum++;
  435. try {
  436. tTrainingService.insertTTraining(t);
  437. successNumber++;
  438. } catch (Exception e) {
  439. failNumber++;
  440. failRow.add(failNum + 1);
  441. }
  442. }
  443. logger.info("list:" + JSON.toJSONString(list));
  444. logger.info("successNumber:" + String.valueOf(successNumber));
  445. logger.info("failNumber:" + String.valueOf(failNumber));
  446. logger.info("failRow:" + String.valueOf(failRow));
  447. return AjaxResult.success(String.valueOf(successNumber), failRow);
  448. }
  449. /**
  450. * 生成报告
  451. */
  452. @RequestMapping(value = "/trainingReport", produces = "application/json;charset=utf-8")
  453. @ResponseBody
  454. public void AutoReport(HttpServletRequest request, HttpServletResponse response, Long year, Long trainingId) {
  455. TTraining tTraining = tTrainingMapper.selectTTrainingById(trainingId);
  456. String tempUrl = "";
  457. if (tTraining.getDeptId() == 103 || tTraining.getDeptId() == 10012) {
  458. if (tTraining.getDeptId() == 10012) {
  459. tempUrl = "static/word/training/signCBPS.docx"; // 模板文件
  460. }
  461. else if (tTraining.getTrainingType().equals("12")) {
  462. tempUrl = "static/word/training/signMOC.docx"; // 模板文件
  463. } else {
  464. tempUrl = "static/word/training/sign.docx"; // 模板文件
  465. }
  466. // 保存结果文
  467. InputStream is = null;
  468. try {
  469. is = Thread.currentThread().getContextClassLoader().getResourceAsStream(tempUrl);
  470. CustomXWPFDocument doc = new CustomXWPFDocument(is);
  471. // 替换word模板数据
  472. replaceAll(doc, year, trainingId);
  473. response.setContentType("application/octet-stream");// 下载,默认就是下载
  474. response.setCharacterEncoding("UTF-8");
  475. response.setHeader("Content-Disposition",
  476. "attachment;fileName=" + URLEncoder.encode(tTraining.getCourse() + ".docx", "UTF-8"));
  477. // 刷新缓冲
  478. response.flushBuffer();
  479. OutputStream ouputStream = response.getOutputStream();
  480. doc.write(ouputStream);
  481. ouputStream.flush();
  482. ouputStream.close();
  483. } catch (Exception e) {
  484. e.printStackTrace();
  485. }
  486. } else {
  487. try {
  488. tempUrl = "static/word/training/signBYX.xlsx"; // 模板文件
  489. InputStream is = null;
  490. is = Thread.currentThread().getContextClassLoader().getResourceAsStream(tempUrl);
  491. XSSFWorkbook wb1 = new XSSFWorkbook(is);
  492. SXSSFWorkbook wb = new SXSSFWorkbook(wb1, 1000);
  493. // 替换excel模板数据
  494. replaceExcel(wb, trainingId);
  495. response.setContentType("application/octet-stream");// 下载,默认就是下载
  496. response.setCharacterEncoding("UTF-8");
  497. response.setHeader("Content-Disposition",
  498. "attachment;fileName=" + URLEncoder.encode(tTraining.getCourse() + ".xlsx", "UTF-8"));
  499. // 刷新缓冲
  500. response.flushBuffer();
  501. OutputStream ouputStream = response.getOutputStream();
  502. wb.write(ouputStream);
  503. ouputStream.flush();
  504. ouputStream.close();
  505. } catch (Exception e) {
  506. e.printStackTrace();
  507. }
  508. }
  509. }
  510. //苯乙烯 Excel 渲染
  511. private void replaceExcel(SXSSFWorkbook wb, Long trainingId) {
  512. Sheet sheet = wb.getSheet("CTAM");
  513. TTraining tTraining = tTrainingMapper.selectTTrainingById(trainingId);
  514. TStaffmgr tStaffmgr = new TStaffmgr();
  515. tStaffmgr.setActualposts(tTraining.getPosition());
  516. tStaffmgr.setDeptId(tTraining.getDeptId());
  517. List<TStaffmgr> staffmgrList = tStaffmgrMapper.selectAllTStaffmgrList(tStaffmgr);
  518. List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("STAFF_UNIT");
  519. try {
  520. //判断离职
  521. if (!org.apache.commons.lang.StringUtils.isEmpty(tTraining.getYear())) {
  522. Iterator<TStaffmgr> iterator = staffmgrList.iterator();
  523. while (iterator.hasNext()) {
  524. TStaffmgr t = iterator.next();
  525. if (t.getLeftDate() != null && t.getDelFlag() == 9) {
  526. if (t.getLeftDate().getTime() - tTraining.getStartDate().getTime() < 0l) {
  527. iterator.remove();
  528. }
  529. }
  530. }
  531. }
  532. } catch (Exception e) {
  533. }
  534. List<TStaffmgr> staffmgrs = new ArrayList<TStaffmgr>();
  535. if (tTraining.getDesignatedStaff() != null) { //判断指定人员
  536. String[] staffIds = tTraining.getDesignatedStaff().split(",");
  537. for (int i = 0; i < staffIds.length; i++) {
  538. TStaffmgr staffmgr = tStaffmgrMapper.selectTStaffmgrByStaffId(staffIds[i]);
  539. staffmgrs.add(staffmgr);
  540. }
  541. staffmgrList.addAll(staffmgrs);
  542. }
  543. replaceSheet(wb,"CTAM",staffmgrList);
  544. replaceSheet(wb,"CTMM",staffmgrList);
  545. replaceSheet(wb,"CTSL",staffmgrList);
  546. replaceSheet(wb,"白班",staffmgrList);
  547. replaceSheet(wb,"班组",staffmgrList);
  548. }
  549. //苯乙烯 Excel 渲染
  550. private void replaceSheet(SXSSFWorkbook wb,String sheetName,List<TStaffmgr> staffmgrList) {
  551. List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("STAFF_UNIT");
  552. Sheet sheet = wb.getSheet(sheetName);
  553. List<TStaffmgr> staffmgrs = new ArrayList<>();
  554. if ("CTAM".equals(sheetName)) {
  555. for (TStaffmgr t: staffmgrList
  556. ) {
  557. if ( t.getUnit().equals("22")){
  558. staffmgrs.add(t);
  559. }
  560. }
  561. }
  562. if ("CTMM".equals(sheetName)) {
  563. for (TStaffmgr t: staffmgrList
  564. ) {
  565. if ( t.getUnit().equals("24")){
  566. staffmgrs.add(t);
  567. }
  568. }
  569. }
  570. if ("CTSL".equals(sheetName)) {
  571. for (TStaffmgr t: staffmgrList
  572. ) {
  573. if ( t.getUnit().equals("16")){
  574. staffmgrs.add(t);
  575. }
  576. }
  577. }
  578. if ("白班".equals(sheetName)) {
  579. for (TStaffmgr t: staffmgrList
  580. ) {
  581. if ( t.getTeam().equals("18") && t.getUnit().equals("20")){
  582. staffmgrs.add(t);
  583. }
  584. }
  585. }
  586. if ("班组".equals(sheetName)) {
  587. for (TStaffmgr t: staffmgrList
  588. ) {
  589. if ( t.getTeam().equals("10") ||t.getTeam().equals("12") ||t.getTeam().equals("14") ||t.getTeam().equals("16") ){
  590. staffmgrs.add(t);
  591. }
  592. }
  593. }
  594. //设置style
  595. CellStyle cellStyle = wb.createCellStyle();
  596. //设置水平对齐方式
  597. cellStyle.setAlignment(HorizontalAlignment.CENTER);
  598. //设置垂直对齐方式
  599. cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  600. cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
  601. cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
  602. cellStyle.setBorderTop(BorderStyle.THIN);//上边框
  603. cellStyle.setBorderRight(BorderStyle.THIN);//右边框
  604. //设置上边框线条颜色
  605. cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
  606. //设置右边框线条颜色
  607. cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
  608. //设置下边框线条颜色
  609. cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
  610. //设置左边框线条颜色
  611. cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
  612. //字体
  613. Font headerFont = wb.createFont();
  614. headerFont.setFontName("Arial");
  615. headerFont.setFontHeightInPoints((short) 11);
  616. cellStyle.setFont(headerFont);
  617. int rowIndex = 7;//初始行数
  618. for (int i = 0; i < staffmgrs.size(); i++) { //加载签名数据
  619. Row row = sheet.createRow(rowIndex);
  620. row.setHeight((short) 400);
  621. row.createCell(0).setCellValue(i + 1);
  622. row.getCell(0).setCellStyle(cellStyle);
  623. row.createCell(1).setCellValue(DictUtils.getDictVale(dictList, staffmgrs.get(i).getUnit()));
  624. row.getCell(1).setCellStyle(cellStyle);
  625. row.createCell(2).setCellValue(staffmgrs.get(i).getStaffid());
  626. row.getCell(2).setCellStyle(cellStyle);
  627. row.createCell(3).setCellValue(staffmgrs.get(i).getName());
  628. row.getCell(3).setCellStyle(cellStyle);
  629. row.createCell(4).setCellStyle(cellStyle);
  630. row.createCell(5).setCellStyle(cellStyle);
  631. if (i + 1 < staffmgrs.size()) {
  632. row.createCell(6).setCellValue(i + 2);
  633. row.getCell(6).setCellStyle(cellStyle);
  634. row.createCell(7).setCellValue(DictUtils.getDictVale(dictList, staffmgrs.get(i + 1).getUnit()));
  635. row.getCell(7).setCellStyle(cellStyle);
  636. row.createCell(8).setCellValue(staffmgrs.get(i + 1).getStaffid());
  637. row.getCell(8).setCellStyle(cellStyle);
  638. row.createCell(9).setCellValue(staffmgrs.get(i + 1).getName());
  639. row.getCell(9).setCellStyle(cellStyle);
  640. row.createCell(10).setCellStyle(cellStyle);
  641. row.createCell(11).setCellStyle(cellStyle);
  642. }
  643. i++;
  644. rowIndex++;
  645. }
  646. sheet.addMergedRegionUnsafe(new CellRangeAddress(rowIndex, rowIndex, 0, 1));
  647. sheet.addMergedRegionUnsafe(new CellRangeAddress(rowIndex, rowIndex, 2, 11));
  648. // 最后一行
  649. Row rowLast = sheet.createRow(rowIndex);
  650. rowLast.setHeight((short) 3000);
  651. rowLast.createCell(0).setCellValue("培训有效性");
  652. rowLast.getCell(0).setCellStyle(cellStyle);
  653. //设置style
  654. CellStyle lastStyle = wb.createCellStyle();
  655. //设置水平对齐方式
  656. lastStyle.setAlignment(HorizontalAlignment.CENTER);
  657. //设置垂直对齐方式
  658. lastStyle.setVerticalAlignment(VerticalAlignment.BOTTOM);
  659. lastStyle.setBorderBottom(BorderStyle.THIN); //下边框
  660. lastStyle.setBorderLeft(BorderStyle.THIN);//左边框
  661. lastStyle.setBorderTop(BorderStyle.THIN);//上边框
  662. lastStyle.setBorderRight(BorderStyle.THIN);//右边框
  663. //设置上边框线条颜色
  664. lastStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
  665. //设置右边框线条颜色
  666. lastStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
  667. //设置下边框线条颜色
  668. lastStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
  669. //设置左边框线条颜色
  670. lastStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
  671. lastStyle.setFont(headerFont);
  672. rowLast.createCell(2).setCellValue(" 签名:");
  673. rowLast.getCell(2).setCellStyle(lastStyle);
  674. rowLast.createCell(1).setCellStyle(cellStyle);
  675. rowLast.createCell(3).setCellStyle(cellStyle);
  676. rowLast.createCell(4).setCellStyle(cellStyle);
  677. rowLast.createCell(5).setCellStyle(cellStyle);
  678. rowLast.createCell(6).setCellStyle(cellStyle);
  679. rowLast.createCell(7).setCellStyle(cellStyle);
  680. rowLast.createCell(8).setCellStyle(cellStyle);
  681. rowLast.createCell(9).setCellStyle(cellStyle);
  682. rowLast.createCell(10).setCellStyle(cellStyle);
  683. rowLast.createCell(11).setCellStyle(cellStyle);
  684. }
  685. /**
  686. * @Description: 替换段落和表格
  687. */
  688. private void replaceAll(CustomXWPFDocument doc, Long year, Long meetingId) throws Exception {
  689. doParagraphs(doc, meetingId);// 处理段落文字数据,包括文字和表格、图片
  690. }
  691. /**
  692. * 处理段落文字数据,包括文字和表格、图片
  693. *
  694. * @param doc 一个文档包含多个段落,一个段落包含多个Runs,一个Runs包含多个Run,Run是文档的最小单元
  695. */
  696. private void doParagraphs(CustomXWPFDocument doc, Long trainingId) throws IOException, InvalidFormatException {
  697. // 文本数据
  698. Calendar cal = Calendar.getInstance();
  699. Map<String, String> textMap = new HashMap<String, String>();
  700. TTraining tTraining = tTrainingService.selectTTrainingById(trainingId);
  701. textMap.put("{{course}}", " " + String.valueOf(tTraining.getCourse()));
  702. //
  703. /**
  704. * 替换表格中指定的文字
  705. */
  706. Iterator<XWPFTable> itTable = doc.getTablesIterator();
  707. int i = 1;
  708. while (itTable.hasNext()) {
  709. XWPFTable table = (XWPFTable) itTable.next();
  710. changeTableMessage(textMap, table, false, null, i, doc, tTraining);
  711. i++;
  712. }
  713. /** ----------------------------处理段落------------------------------------ **/
  714. List<XWPFParagraph> paragraphList = doc.getParagraphs();
  715. if (paragraphList != null && paragraphList.size() > 0) {
  716. for (XWPFParagraph paragraph : paragraphList) {
  717. List<XWPFRun> runs = paragraph.getRuns();
  718. for (XWPFRun run : runs) {
  719. String text = run.getText(0);
  720. logger.info("text======" + text);
  721. if (text != null) {
  722. // 替换文本信息
  723. String tempText = text;
  724. String key = tempText.replaceAll("\\{\\{", "").replaceAll("}}", "");
  725. if (!StringUtils.isEmpty(textMap.get(key))) {
  726. run.setText(textMap.get(key), 0);
  727. }
  728. /**
  729. * ----------------------------替换表格数据
  730. * ------------------------------------
  731. **/
  732. doJLParagraphs(doc, paragraph, run, tempText, trainingId);// 处理段落文字数据,包括文字和表格、图片
  733. }
  734. }
  735. }
  736. }
  737. }
  738. private void changeTableMessage(Map<String, String> textMap, XWPFTable table, boolean isBold, Integer fontSize, int num, CustomXWPFDocument doc, TTraining tTraining) throws IOException, InvalidFormatException {
  739. int count = table.getNumberOfRows();//获取table的行数
  740. //插入图片测试
  741. XWPFTableRow rowTest = table.getRow(0);
  742. for (int i = 0; i < count; i++) {
  743. XWPFTableRow row = table.getRow(i);
  744. List<XWPFTableCell> cells = row.getTableCells();
  745. for (XWPFTableCell cell : cells) {//遍历每行的值并进行替换
  746. logger.info(cell.getText() + ":::::");
  747. for (Map.Entry<String, String> e : textMap.entrySet()) {
  748. if (cell.getText().equals("${picture1}")) {
  749. cell.removeParagraph(0);
  750. //拆入图片
  751. if (tTraining.getPicUrl() != null) {
  752. String[] picList = tTraining.getPicUrl().split(",");
  753. logger.info(tTraining.getPicUrl());
  754. logger.info(JSON.toJSONString(picList));
  755. for (int j = 0; j < picList.length; j++) {
  756. XWPFParagraph newPara = new XWPFParagraph(cell.getCTTc().addNewP(), cell);
  757. cell.addParagraph(newPara);
  758. Map<String, Object> header = new HashMap<String, Object>();
  759. header.put("width", 500);
  760. header.put("height", 500);
  761. if (picList[j].endsWith("jpg")) {
  762. header.put("type", "jpg");
  763. } else if (picList[j].endsWith("png")) {
  764. header.put("type", "png");
  765. }
  766. header.put("content", RuoYiConfig.getProfile() + picList[j].replace("/profile", ""));
  767. String imgUrl = (String) ((Map<?, ?>) header).get("content");
  768. String type = (String) ((Map<?, ?>) header).get("type");
  769. int width = (Integer) ((Map<?, ?>) header).get("width");
  770. int height = (Integer) ((Map<?, ?>) header).get("height");
  771. String blipId = doc.addPictureData(new FileInputStream(new File(imgUrl)), getPictureType(type));
  772. doc.createPicture(blipId, doc.getNextPicNameNumber(getPictureType(type)), width, height, newPara);
  773. }
  774. }
  775. } else if (cell.getText().equals(e.getKey())) {
  776. XWPFParagraph newPara = new XWPFParagraph(cell.getCTTc().addNewP(), cell);
  777. XWPFRun r1 = newPara.createRun();
  778. if (num == 1) {
  779. r1.setFontSize(10);
  780. r1.setTextPosition(10);
  781. r1.setBold(true);
  782. } else if (num == 2) {
  783. r1.setFontSize(13);
  784. r1.setTextPosition(10);
  785. }
  786. r1.setText(e.getValue());
  787. cell.removeParagraph(0);
  788. cell.setParagraph(newPara);
  789. }
  790. }
  791. }
  792. }
  793. }
  794. /**
  795. * 处理段落文字--经理
  796. *
  797. * @param doc
  798. * @throws InvalidFormatException
  799. * @throws FileNotFoundException
  800. * @throws IOException
  801. */
  802. public void doJLParagraphs(CustomXWPFDocument doc, XWPFParagraph paragraph, XWPFRun run, String text, Long meetingId) {
  803. // 执行表
  804. if (text.contains("${table1}")) {
  805. tTrainingService.dealTraininglist(doc, paragraph, run, meetingId);
  806. }
  807. }
  808. /**
  809. * 根据图片类型,取得对应的图片类型代码
  810. *
  811. * @param picType
  812. * @return int
  813. */
  814. private static int getPictureType(String picType) {
  815. int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
  816. if (picType != null) {
  817. if (picType.equalsIgnoreCase("png")) {
  818. res = CustomXWPFDocument.PICTURE_TYPE_PNG;
  819. } else if (picType.equalsIgnoreCase("dib")) {
  820. res = CustomXWPFDocument.PICTURE_TYPE_DIB;
  821. } else if (picType.equalsIgnoreCase("emf")) {
  822. res = CustomXWPFDocument.PICTURE_TYPE_EMF;
  823. } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
  824. res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
  825. } else if (picType.equalsIgnoreCase("wmf")) {
  826. res = CustomXWPFDocument.PICTURE_TYPE_WMF;
  827. }
  828. }
  829. return res;
  830. }
  831. }