前后端分离项目之数据导出为word实例
来源:互联网 发布:手机淘宝信誉度怎么看 编辑:程序博客网 时间:2024/06/05 17:56
1.后台restful api,组装文件输出流对象到response响应包输出到前端(vue+webpack node管理)。
后台接口:根据projectId查询相关数据,并将相关字段封装到word模板中,最后用流输出文件。
控制层代码
@RequestMapping("/exportToWord") @ResponseBody public void exportToWord(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "projectId", required = true) String projectId) { try { String path = request.getSession().getServletContext().getRealPath("\\"); projectDocService.exportToWord(response,projectId,path); } catch (Exception e) { logger.error("事项导出成word失败:", e); } }
业务层代码
public void exportToWord(HttpServletResponse response,String projectId,String path) throws Exception{ HashMap<String,Object> params=new HashMap<String,Object>(); params.put("projectId", projectId); HashMap<String, Object> projectMap = projectDao.queryProjectDetailByPid(params); if(projectMap!=null){ // 导出基本信息 operatorProject(projectMap, path); String downpath = path + "FileDownload/govsdm/Download/project.docx"; String erweimapath = path + "FileDownload/govsdm/QRCode/project.jpg"; String srcpath = path + "FileDownload/govsdm/Export/project.docx"; FileInputStream inputStream = new FileInputStream(erweimapath); Map<String, FileInputStream> maps = new HashMap<String, FileInputStream>( 0); maps.put("$erweima", inputStream); CustomXWPFDocument customXWPFDocument = new CustomXWPFDocument(); // 插入二维码 customXWPFDocument.searchAndReplaceImg(srcpath, downpath, erweimapath, maps); download(downpath, response, projectMap.get("projectName").toString()); } }
导出的word模板如下图:
public void operatorProject(Map<String, Object> projectMap, String path) throws Exception { HashMap<String, Object> map = new HashMap<String, Object>(); //事项基本信息 map.put("${projectNo}", projectMap.get("projectNo")); map.put("${projectName}", projectMap.get("projectName")); map.put("${PROJECTNAMEBIAOTI}", projectMap.get("projectName")); map.put("${deptName}", projectMap.get("deptName")); map.put("${itemName}", projectMap.get("itemName")); map.put("${projectItemNo}", projectMap.get("projectItemNo")); map.put("${projectShowNo}", projectMap.get("projectShowNo")); map.put("${gridNo}", projectMap.get("gridNo")); map.put("${PROJECT_TYPE_NAME}", projectMap.get("PROJECT_TYPE_NAME")); map.put("${SERVICE_TYPE_NAME}", projectMap.get("SERVICE_TYPE_NAME")); map.put("${CASE_TYPE_NAME}", projectMap.get("CASE_TYPE_NAME")); map.put("${DEAL_TYPE_NAME}", projectMap.get("DEAL_TYPE_NAME")); map.put("${TONGBAN_RANGE_NAME}", projectMap.get("TONGBAN_RANGE_NAME")); map.put("${RUN_SYSTEM_TYPE_NAME}", projectMap.get("RUN_SYSTEM_TYPE_NAME")); map.put("${POWER_UPDATE_TYPE_NAME}", projectMap.get("POWER_UPDATE_TYPE_NAME")); map.put("${POWER_STATE_NAME}", projectMap.get("POWER_STATE_NAME")); map.put("${ACCEPTING_RANGE_NAME}", projectMap.get("ACCEPTING_RANGE_NAME")); map.put("${IMPLEMET_SUBJECT_NATURE_NAME}", projectMap.get("IMPLEMET_SUBJECT_NATURE_NAME")); map.put("${AUTHORITY_DIVISION_NAME}", projectMap.get("AUTHORITY_DIVISION_NAME")); map.put("${STREET_DEAL_AUTHORITY_NAME}", projectMap.get("STREET_DEAL_AUTHORITY_NAME")); map.put("${DISTRIBUTE_SYS_TYPE_NAME}", projectMap.get("DISTRIBUTE_SYS_TYPE_NAME")); map.put("${distributeSysUrl}", projectMap.get("distributeSysUrl")); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); String date =sdf.format(new Date()); map.put("${riqi}", date); //查询字典表--审批类型 HashMap<String,Object> projectTypeMap = new HashMap<String,Object>(); projectTypeMap.put("dictCode", "1003"); List<HashMap<String, Object>> projectTypeList = sysDictInfoDao.findList(new RowBounds(), projectTypeMap); String projectType = combinationString(projectTypeList, String.valueOf(projectMap.get("projectType"))); // 事项类型 map.put("${SHIXIANGLEIXING}", projectType); //查询字典表--办理类型 HashMap<String,Object> dealTypeMap = new HashMap<String,Object>(); dealTypeMap.put("dictCode", "1004"); List<HashMap<String, Object>> dealTypeList = sysDictInfoDao.findList(new RowBounds(), dealTypeMap); String dealType = combinationString(dealTypeList, String.valueOf(projectMap.get("dealType"))); // 办理类型 map.put("${BANLILEIXING}", dealType); //办事指南基本信息 HashMap<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("projectId",String.valueOf(projectMap.get("projectId"))); HashMap<String, Object> summaryList = projectSummaryDao.queryProjectSummaryById(paramsMap); summaryList=StringUtils.clobToStringByMap(summaryList);//办事指南信息 List<HashMap<String,Object>> projectFoundationList=projectFoundationDao.findList(new RowBounds(), paramsMap); projectFoundationList=StringUtils.clobToStringByList(projectFoundationList);//设立依据信息 String foundation=""; if(projectFoundationList!=null && projectFoundationList.size()>0){ for(HashMap<String,Object> map1:projectFoundationList){ String categoryName=map1.get("categoryName")==null?"":map1.get("categoryName").toString(); String name=map1.get("name")==null?"":map1.get("name").toString(); String organization=map1.get("organization")==null?"":map1.get("organization").toString(); String issueOrderno=map1.get("issueOrderno")==null?"":map1.get("issueOrderno").toString(); foundation+="["+categoryName+"]"+name+"("+organization+issueOrderno+")"+";"; } } map.put("${foundation}", foundation); // 申请材料清单 String applyMaterial=summaryList.get("applyMaterial")==null?"":summaryList.get("applyMaterial").toString(); map.put("${applyMaterial}", StringEscapeUtils.unescapeHtml(applyMaterial)); //受理标准(条件) String acceptCondition=summaryList.get("acceptCondition")==null?"":summaryList.get("acceptCondition").toString(); map.put("${acceptCondition}", StringEscapeUtils.unescapeHtml(acceptCondition)); //办理(审批)条件 String premitCond=summaryList.get("premitCond")==null?"":summaryList.get("premitCond").toString(); map.put("${premitCond}", StringEscapeUtils.unescapeHtml(premitCond)); //材料审核标准 String materAuditStandard=summaryList.get("materAuditStandard")==null?"":summaryList.get("materAuditStandard").toString(); map.put("${materAuditStandard}", StringEscapeUtils.unescapeHtml(materAuditStandard)); //收费标准 String chargeStandard=summaryList.get("chargeStandard")==null?"":summaryList.get("chargeStandard").toString(); map.put("${chargeStandard}", StringEscapeUtils.unescapeHtml(chargeStandard)); //收费依据 String chargeFoundation=summaryList.get("chargeFoundation")==null?"":summaryList.get("chargeFoundation").toString(); map.put("${chargeFoundation}", StringEscapeUtils.unescapeHtml(chargeFoundation)); //法定办理期限 String statutoryDays=summaryList.get("statutoryDays")==null?"":summaryList.get("statutoryDays").toString(); map.put("${statutoryDays}", StringEscapeUtils.unescapeHtml(statutoryDays)); //法定办理期限描述 String statutoryDesc=summaryList.get("statutoryDesc")==null?"":summaryList.get("statutoryDesc").toString(); map.put("${statutoryDesc}", StringEscapeUtils.unescapeHtml(statutoryDesc)); //承诺办理期限 String promiseDays=summaryList.get("promiseDays")==null?"":summaryList.get("promiseDays").toString(); map.put("${promiseDays}", StringEscapeUtils.unescapeHtml(promiseDays)); //承诺办理期限描述 String promiseDesc=summaryList.get("promiseDesc")==null?"":summaryList.get("promiseDesc").toString(); map.put("${promiseDesc}", StringEscapeUtils.unescapeHtml(promiseDesc)); //业务主管部门 String examAppDept=summaryList.get("examAppDept")==null?"":summaryList.get("examAppDept").toString(); map.put("${examAppDept}", StringEscapeUtils.unescapeHtml(examAppDept)); //实施机构(实施主体) String acceptName=summaryList.get("acceptName")==null?"":summaryList.get("acceptName").toString(); map.put("${acceptName}", StringEscapeUtils.unescapeHtml(acceptName)); //联办机构 String jointlyOrganize=summaryList.get("jointlyOrganize")==null?"":summaryList.get("jointlyOrganize").toString(); map.put("${jointlyOrganize}", StringEscapeUtils.unescapeHtml(jointlyOrganize)); //办理处(科)室 String dealMain=summaryList.get("dealMain")==null?"":summaryList.get("dealMain").toString(); map.put("${dealMain}", StringEscapeUtils.unescapeHtml(dealMain)); //办理地点 String acceptAddress=summaryList.get("acceptAddress")==null?"":summaryList.get("acceptAddress").toString(); map.put("${acceptAddress}", StringEscapeUtils.unescapeHtml(acceptAddress)); //所在窗口 String windowAddress=summaryList.get("windowAddress")==null?"":summaryList.get("windowAddress").toString(); map.put("${windowAddress}", StringEscapeUtils.unescapeHtml(windowAddress)); //办理时间 String workTime=summaryList.get("workTime")==null?"":summaryList.get("workTime").toString(); map.put("${workTime}", StringEscapeUtils.unescapeHtml(workTime)); //中介服务 String intermediaryService=summaryList.get("intermediaryService")==null?"":summaryList.get("intermediaryService").toString(); map.put("${intermediaryService}", StringEscapeUtils.unescapeHtml(intermediaryService)); //数量限制 String quantityRestriction=summaryList.get("quantityRestriction")==null?"":summaryList.get("quantityRestriction").toString(); map.put("${quantityRestriction}", StringEscapeUtils.unescapeHtml(quantityRestriction)); //行使内容(权限说明) String acceptAuthorityDesc=summaryList.get("acceptAuthorityDesc")==null?"":summaryList.get("acceptAuthorityDesc").toString(); map.put("${acceptAuthorityDesc}", StringEscapeUtils.unescapeHtml(acceptAuthorityDesc)); //特别程序及期限 String specialProcedure=summaryList.get("specialProcedure")==null?"":summaryList.get("specialProcedure").toString(); map.put("${specialProcedure}", StringEscapeUtils.unescapeHtml(specialProcedure)); //责任事项 String responsibilityMatters=summaryList.get("responsibilityMatters")==null?"":summaryList.get("responsibilityMatters").toString(); map.put("${responsibilityMatters}", StringEscapeUtils.unescapeHtml(responsibilityMatters)); //责任事项依据 String responsibilityFoundation=summaryList.get("responsibilityFoundation")==null?"":summaryList.get("responsibilityFoundation").toString(); map.put("${responsibilityFoundation}", StringEscapeUtils.unescapeHtml(responsibilityFoundation)); //职责边界 String responsibilityBoundary=summaryList.get("responsibilityBoundary")==null?"":summaryList.get("responsibilityBoundary").toString(); map.put("${responsibilityBoundary}", StringEscapeUtils.unescapeHtml(responsibilityBoundary)); //平均去现场次数 String sceneNum=summaryList.get("sceneNum")==null?"":summaryList.get("sceneNum").toString(); map.put("${sceneNum}", StringEscapeUtils.unescapeHtml(sceneNum)); //办理流程 String process=summaryList.get("process")==null?"":summaryList.get("process").toString(); map.put("${process}", StringEscapeUtils.unescapeHtml(process)); //内部流程描述 String insideProcessDesc=summaryList.get("insideProcessDesc")==null?"":summaryList.get("insideProcessDesc").toString(); map.put("${insideProcessDesc}", StringEscapeUtils.unescapeHtml(insideProcessDesc)); //证照形式及有效期 String certName=summaryList.get("certName")==null?"":summaryList.get("certName").toString(); map.put("${certName}", StringEscapeUtils.unescapeHtml(certName)); //证照名称 String licenseName=summaryList.get("licenseName")==null?"":summaryList.get("licenseName").toString(); map.put("${licenseName}", StringEscapeUtils.unescapeHtml(licenseName)); //填报人 String reporter=summaryList.get("reporter")==null?"":summaryList.get("reporter").toString(); map.put("${reporter}", StringEscapeUtils.unescapeHtml(reporter)); //填报人联系方式 String reporterPhone=summaryList.get("reporterPhone")==null?"":summaryList.get("reporterPhone").toString(); map.put("${reporterPhone}", StringEscapeUtils.unescapeHtml(reporterPhone)); //备注 String remark=summaryList.get("remark")==null?"":summaryList.get("remark").toString(); map.put("${remark}", StringEscapeUtils.unescapeHtml(remark)); //预留字段1 String reserve1=summaryList.get("reserve1")==null?"":summaryList.get("reserve1").toString(); map.put("${reserve1}", StringEscapeUtils.unescapeHtml(reserve1)); //预留字段2 String reserve2=summaryList.get("reserve2")==null?"":summaryList.get("reserve2").toString(); map.put("${reserve2}", StringEscapeUtils.unescapeHtml(reserve2)); //预留字段3 String reserve3=summaryList.get("reserve3")==null?"":summaryList.get("reserve3").toString(); map.put("${reserve3}", StringEscapeUtils.unescapeHtml(reserve3)); //预留字段4 String reserve4=summaryList.get("reserve4")==null?"":summaryList.get("reserve4").toString(); map.put("${reserve4}", StringEscapeUtils.unescapeHtml(reserve4)); //预留字段5 String reserve5=summaryList.get("reserve5")==null?"":summaryList.get("reserve5").toString(); map.put("${reserve5}", StringEscapeUtils.unescapeHtml(reserve5)); //导出模板的文件路径 String srcPath = path + "FileDownload\\govsdm\\Masterplate\\project.docx"; //导出的word路径 String destPath = path + "FileDownload\\govsdm\\Export\\project.docx"; List<HashMap<String, Object>> projectMaterList = projectMaterialsDao.queryProjectMaterialsByPid(paramsMap); projectMaterList=StringUtils.clobToStringByList(projectMaterList);//将clob类型转换为string if(projectMaterList!=null && projectMaterList.size()>0){ searchAndReplaceProject(srcPath, destPath, map,projectMaterList); } }
public static void searchAndReplaceProject(String srcPath, String destPath, HashMap<String, Object> map, List<HashMap<String, Object>> projectMaterialsList) throws IOException { try { File srcDocument = new File(srcPath); OPCPackage pack = POIXMLDocument.openPackage(srcDocument.toString()); XWPFDocument document = new XWPFDocument(pack); // 替换表格中的指定文字 Iterator<XWPFTable> itTable = document.getTablesIterator(); while (itTable.hasNext()) { XWPFTable table = (XWPFTable) itTable.next(); int rcount = table.getNumberOfRows(); for (int i = 0; i < rcount; i++) { XWPFTableRow row = table.getRow(i); List<XWPFTableCell> cells = row.getTableCells(); for (XWPFTableCell cell : cells) { for (Entry<String, Object> e : map.entrySet()) { if (cell.getText().equals(e.getKey())) { cell.removeParagraph(0); XWPFParagraph p=cell.addParagraph(); try { p.createRun().setText(e.getValue().toString()); } catch (Exception e1) { e1.printStackTrace(); } } } } } } try { List<XWPFTable> tableList=document.getTables(); if (tableList!=null&&tableList.size()>0) { int length=tableList.size(); XWPFTable table = (XWPFTable) tableList.get(length-1); for(int i=0;i<projectMaterialsList.size();i++){ XWPFTableRow row=table.createRow(); List<XWPFTableCell> cells = row.getTableCells(); for (int j = 0; j < cells.size(); j++) { XWPFTableCell cell=cells.get(j); cell.removeParagraph(0); CTTcPr tcpr = cell.getCTTc().addNewTcPr(); CTTblWidth cellw = tcpr.addNewTcW(); cellw.setType(STTblWidth.DXA); cellw.setW(BigInteger.valueOf(360*5)); if(j==0){ cell.setText(String.valueOf(projectMaterialsList.get(i).get("materialName"))); }if(j==1){ cell.setText(String.valueOf(projectMaterialsList.get(i).get("description"))); }if(j==2){ if("01".equals(projectMaterialsList.get(i).get("materialType"))) { cell.setText("■文本类 □表格类 □结果文书类 □其它类"); }else if("02".equals(projectMaterialsList.get(i).get("materialType"))) { cell.setText("□文本类 ■表格类 □结果文书类 □其它类"); }else if("03".equals(projectMaterialsList.get(i).get("materialType"))) { cell.setText("□文本类 □表格类 ■结果文书类 □其它类"); }else { cell.setText("□文本类 □表格类 □结果文书类 ■其它类"); } } } } } FileOutputStream outStream = null; outStream = new FileOutputStream(destPath); document.write(outStream); outStream.close(); } catch (Exception e) { e.printStackTrace(); } /////////////////给WORD插入标题/////////////// //获得第一个段落对象 XWPFParagraph paragraph = document.getParagraphs().get(3); //段落的格式,下面及个设置,将使新添加的文字向左对其,无缩进. paragraph.setIndentationLeft(0); paragraph.setIndentationHanging(0); paragraph.setWordWrap(true); //在段落中新插入一个run,这里的run我理解就是一个word文档需要显示的个体,里面可以放文字,参数0代表在段落的最前面插入 XWPFRun run = paragraph.insertNewRun(0); //设置run内容 run.setText(map.get("${PROJECTNAMEBIAOTI}")+""); run.setFontFamily("宋体"); run.setBold(true); run.setFontSize(20); FileOutputStream outStream = null; outStream = new FileOutputStream(destPath); document.write(outStream); outStream.flush(); outStream.close(); }catch (Exception e) { e.printStackTrace(); } }
private String combinationString(List<HashMap<String, Object>> list, String type) { String cString = ""; String[] typeArr = type.split(","); boolean isSelected = false; for (int i = 0; i < list.size(); i++) { isSelected = false; for(String type1 : typeArr){ if (list.get(i).get("dictId").equals(type1)) { isSelected = true; } } if (isSelected) { cString += "■" + list.get(i).get("dictName") + " "; }else{ cString += "□" + list.get(i).get("dictName") + " "; } } return cString; }
最后输出文件流
public HttpServletResponse download(String path, HttpServletResponse response, String projectname) throws Exception { // path是指欲下载的文件的路径。 File file = new File(path); // 以流的形式下载文件。 InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 设置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + new String((projectname + ".docx").getBytes("gbk"), "iso-8859-1")); response.addHeader("Content-Length", "" + file.length()); OutputStream toClient = new BufferedOutputStream( response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); return response; }
前端vue代码片段;
<Button type="warning" size="small" @click="exports(item.projectId)" icon="share" v-if="btnData.indexOf('export')!==-1">导出</Button>
js代码
//导出 exports(projectId){ let token = localStorage.getItem('token'); //自定义form标签,初始化相关参数 var form = $("<form>"); form.attr('style', 'display:none'); form.attr('target', ''); form.attr('method', 'post'); form.attr('action', window.config.api + '/projectDocController/exportToWord.do'); var input1 = $('<input>'); input1.attr('type', 'hidden'); input1.attr('name', 'projectId'); input1.attr('value', projectId); var input2 = $('<input>'); input2.attr('type', 'hidden'); input2.attr('name', 'token'); input2.attr('value', token); $('body').append(form); form.append(input1); form.append(input2); form.submit(); form.remove(); }
小结:针对文件流的操作,尽量用提交form表单的形式处理请求。
阅读全文
0 0
- 前后端分离项目之数据导出为word实例
- 构建SpringMVCRestful前后端分离项目实例
- 前后端分离之Java后端
- 前后端分离之Springboot后端
- 前后端分离——前后端数据交互
- 前后端分离项目实践分析
- 前后端分离项目实践分析
- 前后端分离项目:后台管理
- 前后端分离项目shiro验证
- Javaweb项目如何做到前后端分离
- 前后端完全分离之API设计
- vue前后端分离之前端搭建
- 前后端分离之VueJS前端
- 前后端分离之JWT用户认证
- 前后端分离之VueJS前端
- 前后端分离之本地数据调试——mockJs的应用
- web前后端分离
- 前后端分离
- MYSQL初学者使用指南
- 微信小程序
- nodejs express 子app功能(路由)
- [LeetCode] 628. Maximum Product of Three Numbers
- Android中资源文件夹res/raw和assets的使用
- 前后端分离项目之数据导出为word实例
- Django编写第一个博客学习笔记(二)
- 自定义表单验证--jquery validator addMethod的使用
- 一、登录Oracle和创建用户
- 树莓派新系统SSH连接被拒绝的解决方法
- SQL不同数据库拼接字符串
- Vim技能修炼教程(8)
- Servlet—包—的错误
- IO复用函数select poll epoll