js 去掉 <!--[if gte vml 1]><!--[endif]-->

本文介绍了一种处理富文本中特定标记的方法,通过JavaScript实现去除不兼容的富文本标记,确保了浏览器正确显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前端在处理后台用富文本编辑后传来的数据时,带有:

<!--[if gte vml 1]><![endif]-->

<!--[if gte vml 1]><v:shapetype
 id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t"
 path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f">
 <v:stroke joinstyle="miter"/>
 <v:formulas>
  <v:f eqn="if lineDrawn pixelLineWidth 0"/>
  <v:f eqn="sum @0 1 0"/>
  <v:f eqn="sum 0 0 @1"/>
  <v:f eqn="prod @2 1 2"/>
  <v:f eqn="prod @3 21600 pixelWidth"/>
  <v:f eqn="prod @3 21600 pixelHeight"/>
  <v:f eqn="sum @0 0 1"/>
  <v:f eqn="prod @6 1 2"/>
  <v:f eqn="prod @7 21600 pixelWidth"/>
  <v:f eqn="sum @8 21600 0"/>
  <v:f eqn="prod @7 21600 pixelHeight"/>
  <v:f eqn="sum @10 21600 0"/>
 </v:formulas>
 <v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/>
 <o:lock v:ext="edit" aspectratio="t"/>
</v:shapetype><v:shape id="图片_x0020_3" o:spid="_x0000_i1025" type="#_x0000_t75"
 style='width:5in;height:240pt'>
 <v:imagedata src="file:///C:\Users\ADMINI~1\AppData\Local\Temp\msohtmlclip1\01\clip_image001.jpg"
  o:href="http://p2.ifengimg.com/a/2017_38/9ea0304b6ba1fc3_size1489_w2500_h1668.jpg"/>
</v:shape><![endif]-->

1 可以用正则去掉:

 貌似js不支持这种“(?<=(”,

2   js把这段字符串截取掉, 实例如

//处理富文本中的[if gte vml 1]
function ifGteVml(str){
    var w=str.indexOf("<!--[if gte vml 1]>");
    var w2=str.indexOf("--></span>");
    var curStr = str.substring(w,w2+3);
    return str.replace(curStr, '');
}





public static String exportHtmlToWord( String content, String fileName,String path,String type) throws Exception { // 拼接html格式内容 StringBuffer sbf = new StringBuffer(); // 这里拼接一下html标签,便于word文档能够识别 sbf.append("<html " + "xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\" xmlns=\"http://www.w3.org/TR/REC-html40\"" + //将版式从web版式改成页面试图 ">"); sbf.append("<head>" + "<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val=\"Cambria Math\"/><m:brkBin m:val=\"before\"/><m:brkBinSub m:val=\"--\"/><m:smallFrac m:val=\"off\"/><m:dispDef/><m:lMargin m:val=\"0\"/> <m:rMargin m:val=\"0\"/><m:defJc m:val=\"centerGroup\"/><m:wrapIndent m:val=\"1440\"/><m:intLim m:val=\"subSup\"/><m:naryLim m:val=\"undOvr\"/></m:mathPr></w:WordDocument></xml><![endif]-->" + "</head>"); sbf.append("<body>"); // 富文本内容 sbf.append("<div >"+content+"</div>"); sbf.append("</body></html>"); // 必须要设置编码,避免中文就会乱码 byte[] b = sbf.toString().getBytes("GBK"); // 将字节数组包装到流中 ByteArrayInputStream bais = new ByteArrayInputStream(b); POIFSFileSystem poifs = new POIFSFileSystem(); DirectoryEntry directory = poifs.getRoot(); // 这代码不能省略,否则导出乱码。 DocumentEntry documentEntry = directory.createDocument("WordDocument", bais); // //输出文件 // request.setCharacterEncoding("utf-8"); // 导出word格式 // response.setContentType("application/msword"); // response.addHeader("Content-Disposition", "attachment;filename=" + // new String(fileName.getBytes("GB2312"),"iso8859-1") + ".doc"); // ServletOutputStream ostream = response.getOutputStream(); // poifs.writeFilesystem(ostream); // bais.close(); // ostream.close(); String fileAddress = path + "/"+type+"/" + fileName + ".doc"; // FileCopyUtils.copy(poifs.createDocumentInputStream("WordDocument"), new FileOutputStream(fileAddress)); return fileAddress; } 我需要转换成docx格式,请按照这个修改
05-24
@Override public void createArticleOutputFromTemplateHttp(HttpServletRequest request, HttpServletResponse response, ArticleData articleData) { if (articleData==null){ log.warn("勾选模板内容生成word文档的参数为空,不作处理,返回。"); return; } // 获取勾选的内容 Long[] ids = articleData.getIds(); if (ids==null || ids.length<=0){ log.warn("没有选择需要生成word文档的数据,不作处理,返回。"); return; } // 是否导出备注详情 int notesExportFlag = articleData.getNotesExportFlag(); // 导出数据准备---------------------------------- List<ArticleData> articleDataList = articleDataMapper.selectArticleDataByIds(ids); if (articleDataList==null || articleDataList.size()<=0){ log.warn("获取的word文档数据为空,不作处理,返回。"); return; } // 批量获取模块数据 ,然后进行排序======================================= // Long[] menu_ids = new Long[articleDataList.size()]; // for(int i=0;i<articleDataList.size();i++){ // menu_ids[i] = articleDataList.get(i).getMenuId(); // } // List<ArticleMenu> menu_list = articleMenuMapper.selectArticleMenuByMenuIds(menu_ids); // // 排序 // Collections.sort(menu_list, new Comparator<ArticleMenu>() { // @Override // public int compare(ArticleMenu o1, ArticleMenu o2) { // // TODO Auto-generated method stub // int flag = (int) (o1.getParentId()-o2.getParentId()); // if(flag == 0){ // flag = (int) (o1.getOrderNum()-o2.getOrderNum()); // } // return flag; // } // }); // ================================================================== // 获取数据 有序数据 // articleData.setMenuIds(menu_ids); // articleDataList = articleDataMapper.selectArticleDataByMenuIdsOrder(articleData); //各个 Long 含义: 层级、menuId(原先为父类模块ID)、排序order_num(注?:确保排序唯一),最底层map:数据、父类ID、排序 Map<Integer,Map<Long, Map<Long, List<Map<String, Object>>>>> myDatasMap = new HashMap<Integer,Map<Long, Map<Long, List<Map<String, Object>>>>>(); //菜单最深层数 int maxLevel = 1; // 菜单纵信息 List<Long[]> list_coloum = new ArrayList<Long[]>(); // 菜单纵信息及后面按显示顺序排序 List<String[]> list_coloum_str = new ArrayList<String[]>(); // 获取模块目录信息 for(ArticleData param : articleDataList){ //这里导出的时候加上备注的内容 if(notesExportFlag>0 && StringUtils.isNotBlank(param.getNotes())){ param.setContent(param.getContent() +"<p><br/></p>" +"<p>***备注***:</p>" +"<p>"+param.getNotes()+"</p>"); } ArticleMenu menu = articleMenuMapper.selectArticleMenuByMenuId(param.getMenuId()); String[] menuIdArr = menu.getAncestors().split(","); Long[] menuIdsArr = new Long[menuIdArr.length+1]; // 用于排序(menu_id 和 序号 综合排) String[] menuIdsSort = new String[menuIdArr.length+1]; if(menuIdArr!=null && menuIdArr.length>0){ for(int i=0;i<menuIdArr.length;i++){ menuIdsArr[i] = Long.parseLong(menuIdArr[i].trim()); if(i>0){ ArticleMenu menu_temp = articleMenuMapper.selectArticleMenuByMenuId(Long.parseLong(menuIdArr[i].trim())); menuIdsSort[i] = menuIdArr[i].trim()+"&&"+menu_temp.getOrderNum(); }else{ menuIdsSort[i] = menuIdArr[i].trim(); } } } menuIdsArr[menuIdArr.length] = menu.getMenuId(); list_coloum.add(menuIdsArr); menuIdsSort[menuIdArr.length] = menu.getMenuId()+"&&"+menu.getOrderNum(); list_coloum_str.add(menuIdsSort); if(StringUtils.isNotBlank(param.getArticleVersion())){ param.setTitle(param.getTitle()+"(v"+param.getArticleVersion()+"版本)"); } // 解析获取模块信息-横信息 getArticleMenus(myDatasMap,maxLevel,menuIdsArr,param); } // 数据处理 if(myDatasMap != null && myDatasMap.size()>0){ String resourcePath = System.getProperty("user.dir") + "/src/main/resources/"; log.info("项目resource路径 resourcePath:"+resourcePath); List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>(); StringBuffer titleSb = new StringBuffer(); // 存放已经遍历到并处理的模块ID List<Long> menus_handled = new ArrayList<Long>(); // 记录多于1个模块的最深层数 int max_level = 0; int max_level_content = 0; // 菜单序号 int menu_num = 0; int ch_menu_num = 0; int ch2_menu_num = 0; int ch3_menu_num = 0; //按menu_id升序排序,之前使用的--20241016 // Collections.sort(list_coloum, new Comparator<Long[]>() { // @Override // public int compare(Long[] o1, Long[] o2) { // // TODO Auto-generated method stub // int flag = 0; // int len = o1.length>o2.length?o2.length:o1.length; // for(int i=0;i<len;i++){ // int diff = (int) (o1[i]-o2[i]); // flag = flag+diff; // } // return flag; // } // }); //按显示顺序升序排序list_coloum_str Collections.sort(list_coloum_str, new Comparator<String[]>() { @Override public int compare(String[] o1, String[] o2) { // TODO Auto-generated method stub int flag = 0; int len = o1.length>o2.length?o2.length:o1.length; for(int i=1;i<len;i++){ int num1 = Integer.parseInt(o1[i].split("&&")[1].trim()); int num2 = Integer.parseInt(o2[i].split("&&")[1].trim()); int diff = num1 - num2; flag = flag+diff; if(flag!=0){ break; } } return flag; } }); // for(Long[] arr_coloum : list_coloum){ // mu:for(int i=0;i<arr_coloum.length;i++){ // // 当前menuID // Long current_menu_id = arr_coloum[i]; for(String[] arr_coloum : list_coloum_str){ mu:for(int i=0;i<arr_coloum.length;i++){ // 当前menuID Long current_menu_id = Long.parseLong(arr_coloum[i].split("&&")[0].trim()); if(current_menu_id==null || current_menu_id==0 || current_menu_id.equals(0)){ continue; } if(menus_handled!=null&&menus_handled.size()>0){ for(Long menuid_handled : menus_handled){ if(menuid_handled.equals(current_menu_id)){ // 已处理的,就跳过 continue mu; } } } //层级、menuId(现为父类模块ID)、排序order_num(注?:确保排序唯一) Map<Long, Map<Long, List<Map<String, Object>>>> current_menu = myDatasMap.get(i); if(current_menu!=null && current_menu.size()>0){ List<Long> contentMenuIdsExist = new ArrayList<Long>(); for(Long current_parent_id : current_menu.keySet()){ Map<Long, List<Map<String, Object>>> current_parent_map = current_menu.get(current_parent_id); if(current_parent_map!=null && current_parent_map.size()>0){ for(Long current_order_num : current_parent_map.keySet()){ List<Map<String, Object>> current_order_list = current_parent_map.get(current_order_num); if(current_order_list!=null && current_order_list.size()>0){ for(Map<String, Object> current_order_map : current_order_list){ Long menuid = (Long) current_order_map.get("menuId"); if(current_menu_id.equals(menuid)){ log.info("项目resource路径 resourcePath:"+current_menu_id); // 层级、menuId(现为父类模块ID)、排序order_num(注?:确保排序唯一) int current_level_order = (int) current_order_map.get("menuLevel"); if(current_menu.size()==1 && current_parent_map.size()==1 && current_order_list.size() == 1 && (max_level_content==0 || (max_level_content>0 &&current_level_order<max_level_content ))){ //说明该模块只有一个,这里作为标题 if(max_level_content>0){ if(current_level_order<max_level_content){ titleSb.append(current_order_map.get("menuName")+"_"); max_level = current_level_order; } }else{ titleSb.append(current_order_map.get("menuName")+"_"); max_level = current_level_order; } }else{ boolean isExist = false; if(contentMenuIdsExist!=null&&contentMenuIdsExist.size()>0){ for(Long menuKey : contentMenuIdsExist){ if(menuKey.equals(menuid)){ isExist = true; break; } } } if(!isExist){ int current_level = (int) current_order_map.get("menuLevel"); int level = current_level-max_level<1?1:current_level-max_level; if(current_level>max_level_content){ max_level_content = current_level; } // 给目录加上序号 String title_num = ""; if(level==1){ menu_num++; ch_menu_num = 0; //层级有变化,低一级目录序号清零 ch2_menu_num=0; ch3_menu_num=0; if(menu_num==1){ title_num = "一."; }else if(menu_num==2){ title_num = "二."; }else if(menu_num==3){ title_num = "三."; }else if(menu_num==4){ title_num = "四."; }else if(menu_num==5){ title_num = "五."; }else if(menu_num==6){ title_num = "六."; }else if(menu_num==7){ title_num = "七."; }else if(menu_num==8){ title_num = "八."; }else if(menu_num==9){ title_num = "九."; }else if(menu_num==10){ title_num = "十."; }else if(menu_num==11){ title_num = "十一."; }else if(menu_num==12){ title_num = "十二."; }else if(menu_num==13){ title_num = "十三."; }else if(menu_num==14){ title_num = "十四."; }else if(menu_num==15){ title_num = "十五."; }else if(menu_num==16){ title_num = "十六."; }else if(menu_num==17){ title_num = "十七."; }else if(menu_num==18){ title_num = "十八."; }else if(menu_num==19){ title_num = "十九."; }else if(menu_num==20){ title_num = "二十."; }else if(menu_num==21){ title_num = "二十一."; }else if(menu_num==22){ title_num = "二十二."; }else if(menu_num==23){ title_num = "二十三."; }else if(menu_num==24){ title_num = "二十四."; }else if(menu_num==25){ title_num = "二十五."; }else if(menu_num==26){ title_num = "二十六."; }else if(menu_num==27){ title_num = "二十七."; }else if(menu_num==28){ title_num = "二十八."; }else if(menu_num==29){ title_num = "二十九."; }else if(menu_num==30){ title_num = "三十."; } } if(level==2){ ch_menu_num++; ch2_menu_num=0; ch3_menu_num=0; title_num = menu_num+"."+ch_menu_num; } if(level==3){ ch2_menu_num++; ch3_menu_num=0; title_num = menu_num+"."+ch_menu_num+"."+ch2_menu_num; } if(level==4){ ch3_menu_num++; title_num = menu_num+"."+ch_menu_num+"."+ch2_menu_num+"."+ch3_menu_num; } Map<String, Object> wordData = new HashMap<>(); wordData.put("directory", title_num+" "+current_order_map.get("menuName")); Map<String, Object> wordDataMap = new HashMap<>(); wordDataMap.put("templateParth", resourcePath+"templates/bms_menu"+level+".docx"); wordDataMap.put("wordData", wordData); dataList.add(wordDataMap); } } if(current_order_map.get("content")!=null){ //加载内容 ArticleData current_article_data = (ArticleData) current_order_map.get("content"); if(current_article_data!=null){ int current_level = (int) current_order_map.get("menuLevel"); int level = current_level-max_level<1?1:current_level-max_level+1; if(current_level>max_level_content){ max_level_content = current_level; } // 给目录加上序号 String title_num = ""; if(level==1){ menu_num++; ch_menu_num = 0; //层级有变化,低一级目录序号清零 ch2_menu_num=0; ch3_menu_num=0; if(menu_num==1){ title_num = "一."; }else if(menu_num==2){ title_num = "二."; }else if(menu_num==3){ title_num = "三."; }else if(menu_num==4){ title_num = "四."; }else if(menu_num==5){ title_num = "五."; }else if(menu_num==6){ title_num = "六."; }else if(menu_num==7){ title_num = "七."; }else if(menu_num==8){ title_num = "八."; }else if(menu_num==9){ title_num = "九."; }else if(menu_num==10){ title_num = "十."; }else if(menu_num==11){ title_num = "十一."; }else if(menu_num==12){ title_num = "十二."; }else if(menu_num==13){ title_num = "十三."; }else if(menu_num==14){ title_num = "十四."; }else if(menu_num==15){ title_num = "十五."; }else if(menu_num==16){ title_num = "十六."; }else if(menu_num==17){ title_num = "十七."; }else if(menu_num==18){ title_num = "十八."; }else if(menu_num==19){ title_num = "十九."; }else if(menu_num==20){ title_num = "二十."; }else if(menu_num==21){ title_num = "二十一."; }else if(menu_num==22){ title_num = "二十二."; }else if(menu_num==23){ title_num = "二十三."; }else if(menu_num==24){ title_num = "二十四."; }else if(menu_num==25){ title_num = "二十五."; }else if(menu_num==26){ title_num = "二十六."; }else if(menu_num==27){ title_num = "二十七."; }else if(menu_num==28){ title_num = "二十八."; }else if(menu_num==29){ title_num = "二十九."; }else if(menu_num==30){ title_num = "三十."; } } if(level==2){ ch_menu_num++; ch2_menu_num=0; ch3_menu_num=0; title_num = menu_num+"."+ch_menu_num; } if(level==3){ ch2_menu_num++; ch3_menu_num=0; title_num = menu_num+"."+ch_menu_num+"."+ch2_menu_num; } if(level==4){ ch3_menu_num++; title_num = menu_num+"."+ch_menu_num+"."+ch2_menu_num+"."+ch3_menu_num; } //目录 Map<String, Object> wordData = new HashMap<>(); wordData.put("directory", " "+title_num+" "+current_article_data.getTitle()); Map<String, Object> wordDataMap = new HashMap<>(); //int current_level = (int) current_order_map.get("menuLevel"); //int level = current_level-max_level<1?1:current_level-max_level; wordDataMap.put("templateParth", resourcePath+"templates/bms_menu"+level+".docx"); wordDataMap.put("wordData", wordData); dataList.add(wordDataMap); // 内容 Map<String, Object> theData = new HashMap<>(); //=================================================================== // 测试内容 <p><img src="/dev-api/profile/upload/2024/07/30/bef0dd24-730b-41e7-946d-b1f86b09149f-(12) 亿纬_EVE-ICR18650_26V _ 知识管理 - PingCode.png" alt="" width="872" height="436" /></p> // File inputFile = new File("D:/Users/2104020051/Desktop/一些文件/富文本导入导出/亿纬_EVE-ICR18650_26V _ 知识管理 - PingCode.png"); // String base64 = ImageConvertBase64.toBase64(inputFile, true); // log.info("base64="+base64.substring(0, 200)+"......"); // String temp_img = "<p><img src=\""+base64+"\" alt=\"\" width=\"872\" height=\"436\" /></p>"; //==================================================================== ////theData.put("menu", current_article_data.getTitle()); //theData.put("content", current_article_data.getContent()!=null? // current_article_data.getContent().replaceAll("/dev-api/profile", RuoYiConfig.getProfile())+temp_img // :"<span style=\"color: red;\">~标题为:"+current_article_data.getTitle()+"(id="+current_article_data.getId()+")的内容为空</span>"); //针对内容的处理,主要是导出的时候图片的问题 String content = ""; if(current_article_data.getContent()!=null){ //文本编辑器类型(1:Quill富文本编辑器 2:CherryMarkdown 3:Tinymce富文本编辑器) int content_type = Integer.parseInt(current_article_data.getContentType().trim()); if(content_type==1){ content = current_article_data.getContent(); }else if(content_type==2 || content_type==3){ //2:CherryMarkdown 3:Tinymce富文本编辑器 List<String> imgValues = PoiWordUtil.getTagAttributeValues(current_article_data.getContent(), "img", "src"); if(imgValues!=null && imgValues.size()>0){ // 有图片时 content = current_article_data.getContent(); for (String value : imgValues) { String[] image_url_arr = value.split(Constants.RESOURCE_PREFIX); if(image_url_arr!=null && image_url_arr.length>=2){ //String image_url_local = value.replaceAll("/dev-api/profile", RuoYiConfig.getProfile()); //图片全路径 String image_url_local = RuoYiConfig.getProfile()+image_url_arr[1]; //图片全路径 log.info("图片路径="+image_url_local); //image_url_local = "D:/Users/2104020051/Desktop/一些文件/富文本导入导出/亿纬_EVE-ICR18650_26V _ 知识管理 - PingCode.png"; //"E:/ruoyi/uploadPath/upload/2024/07/30/bef0dd24-730b-41e7-946d-b1f86b09149f-(12) 亿纬_EVE-ICR18650_26V _ 知识管理 - PingCode.png"; File inputFile = new File(image_url_local); String base64 = ImageConvertBase64.toBase64(inputFile, true); log.info("base64="+base64.substring(0, 200)+"......"); log.info("value="+value); content = content.replace(value, base64); } } }else{ content = current_article_data.getContent(); } } }else{ content = "<span style=\"color: red;\">~标题为:"+current_article_data.getTitle()+"(id="+current_article_data.getId()+")的内容为空</span>"; } theData.put("content", content); Map<String, Object> wordDataMap2 = new HashMap<>(); wordDataMap2.put("templateParth", resourcePath+"templates/bms_content.docx"); wordDataMap2.put("wordData", theData); dataList.add(wordDataMap2); contentMenuIdsExist.add(menuid); } } menus_handled.add((Long) current_order_map.get("menuId")); // 加入已处理集合 } } } } } } } } } Map<String, Object> wordHead_test = new HashMap<>(); wordHead_test.put("title", titleSb.substring(0, titleSb.length()-1)); wordHead_test.put("currentTime", DateUtils2.getCurrentDateTime()); //首页数据 Map<String, Object> wordHeadMap_test = new HashMap<>(); wordHeadMap_test.put("templateParth", resourcePath+"templates/bms_title.docx"); wordHeadMap_test.put("wordData", wordHead_test); // 上传文件路径 //String filePath = RuoYiConfig.getPathWithTemplePack(); // 新文件名称 //String current = DateUtils2.format(new Date(), "yyyyMMddHHmmssSSS"); //IdUtils.fastUUID() //String fileName = DateUtils.datePath() + "/"+ "Demo报告-"+ current +".docx"; //String documentName = titleSb+ current +".docx"; //String fileName = DateUtils.datePath() + File.separator + documentName; try { //File desc = FileUploadUtils.getAbsoluteFile(filePath, fileName); //String descLocalUrl = desc.getAbsolutePath(); //log.info("导出路径descLocalUrl:"+descLocalUrl);; // 生成并导出word文档 //PoiWordUtil.createDocxManyForRTFHtml(wordHeadMap_test, dataList, descLocalUrl); PoiWordUtil.createDocxManyForRTFHtmlWithHttp(wordHeadMap_test,dataList,request, response); //WordUtil.createDocxMany(wordHeadMap_test, dataList, descLocalUrl); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * 多XWPFTemplate合并成一个word导出,http导出 * @param headMap * @param dataList * @param destParth */ public static void createDocxManyForRTFHtmlWithHttp(Map<String, Object> headMap,List<Map<String, Object>> dataList,HttpServletRequest request, HttpServletResponse response) { LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy(); Configure config = Configure.builder().useSpringEL() .bind("list", policy).build(); // 首页标题 String templateParth_head = headMap.get("templateParth")!=null?String.valueOf(headMap.get("templateParth")).trim():""; Map<String, Object> wordData_head = headMap.get("wordData")!=null?(Map<String, Object>) headMap.get("wordData"):null; if(StringUtils.isBlank(templateParth_head) || wordData_head==null){ log.warn("首页标题参数异常,不作解析导出"); return; } XWPFTemplate template_head = XWPFTemplate.compile(templateParth_head,config).render(wordData_head);// 首页数据调用模板,填充数据 if(dataList==null || dataList.size()<=0){ log.warn("模块数据为空,不作解析导出"); return; } try { //多文档集合 List<NiceXWPFDocument> list = new ArrayList<NiceXWPFDocument>(); NiceXWPFDocument niceXWPFDocument = template_head.getXWPFDocument(); // 生成目录 -------------------------------------------------------------- // 创建标题 XWPFParagraph title = niceXWPFDocument.createParagraph(); XWPFRun titleRun = title.createRun(); //空一行 titleRun.setText(""); // 设置为空字符串来创建一个新的段落 titleRun.addCarriageReturn(); // 确保这个运行不会与前一个运行合并 //空一行 titleRun = title.createRun(); titleRun.setText(""); // 设置为空字符串来创建一个新的段落 titleRun.addCarriageReturn(); // 确保这个运行不会与前一个运行合并 titleRun = title.createRun(); titleRun.setText("目录"); titleRun.setFontSize(16); titleRun.setBold(true); //空一行 titleRun = title.createRun(); titleRun.setText(""); // 设置为空字符串来创建一个新的段落 titleRun.addCarriageReturn(); // 确保这个运行不会与前一个运行合并 niceXWPFDocument.enforceUpdateFields(); CTAbstractNum cTAbstractNum = CTAbstractNum.Factory.newInstance(); XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum); XWPFNumbering numbering = niceXWPFDocument.createNumbering(); BigInteger numID = numbering.addAbstractNum(abstractNum); BigInteger numberingID = numbering.addNum(numID); // 插入目录 XWPFParagraph toc = niceXWPFDocument.createParagraph(); toc.setPageBreak(true); toc.setWordWrap(true); toc.setAlignment(ParagraphAlignment.CENTER); CTP ctP = toc.getCTP(); CTSimpleField tocField = ctP.addNewFldSimple(); tocField.setInstr("TOC \\o \"1-3\" \\h \\z \\u"); toc.getCTP().addNewR().addNewFldChar().setFldCharType(STFldCharType.END); // 生成目录end------------------------------------------------------------- XWPFRun runs = niceXWPFDocument.createParagraph().createRun(); //int num = 0; for(Map<String, Object> dataMap : dataList){ String templateParth_data = dataMap.get("templateParth")!=null?String.valueOf(dataMap.get("templateParth")).trim():""; Map<String, Object> wordData_data = dataMap.get("wordData")!=null?(Map<String, Object>) dataMap.get("wordData"):null; if(StringUtils.isBlank(templateParth_data) || wordData_data==null){ log.warn("模版数据参数异常,该数据不作解析导出,下一条.."); continue; } XWPFTemplate template_data = null;//XWPFTemplate.compile(templateParth_data,config).render(wordData_data);// wordData数据调用模板,填充数据 // 富文本的数据 if(wordData_data.get("content")!=null){ String content = (String) wordData_data.get("content"); String tmpContent = content.replace("<", "<").replace(">", ">").replace(""", "\"").replace("&", "&"); // 拼接html格式内容 StringBuffer sbf = new StringBuffer(); // 这里拼接一下html标签,便于word文档能够识别 sbf.append("<html " + "xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\" xmlns=\"http://www.w3.org/TR/REC-html40\"" + //将版式从web版式改成页面试图 ">"); sbf.append("<head>" + "<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val=\"Cambria Math\"/><m:brkBin m:val=\"before\"/><m:brkBinSub m:val=\"--\"/><m:smallFrac m:val=\"off\"/><m:dispDef/><m:lMargin m:val=\"0\"/> <m:rMargin m:val=\"0\"/><m:defJc m:val=\"centerGroup\"/><m:wrapIndent m:val=\"1440\"/><m:intLim m:val=\"subSup\"/><m:naryLim m:val=\"undOvr\"/></m:mathPr></w:WordDocument></xml><![endif]-->" + "</head>"); sbf.append("<body>"); // 富文本内容 sbf.append(tmpContent); sbf.append("</body></html>"); HtmlRenderPolicy htmlRenderPolicy1 = new HtmlRenderPolicy(); Configure configure1 = Configure.builder() .bind("content", htmlRenderPolicy1) .build(); Map<String, Object> data1 = new HashMap<>(); data1.put("content", sbf.toString()); template_data = XWPFTemplate.compile(templateParth_data, configure1).render(data1); }else{ template_data = XWPFTemplate.compile(templateParth_data,config).render(wordData_data); } list.add(template_data.getXWPFDocument()); template_data.close(); } NiceXWPFDocument newDoc = niceXWPFDocument.merge(list,runs); //合并多个 //FileOutputStream out = new FileOutputStream(destParth);//要导出的文件名 //输出文件 request.setCharacterEncoding("utf-8"); //request.setAttribute(paramString, paramObject);.setAsyncTimeout(10000); //导出word格式"application/msword" -doc "application/vnd.openxmlformats-officedocument.wordprocessingml.document" -docx response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); //response.setHeader("Access-Control-Expose-Headers","Content-disposition"); response.addHeader("Content-Disposition", "attachment;filename=" + wordData_head.get("title") + ".docx"); //过期时间设置 //response.setDateHeader("expires",System.currentTimeMillis() + 60 * 1000); ServletOutputStream out = response.getOutputStream(); newDoc.write(out); out.flush(); out.close(); newDoc.close(); niceXWPFDocument.close(); template_head.close(); log.info("导出生成完成..."); } catch (Exception e) { e.printStackTrace(); } } 这是导出文档的两个方法,现在文档内容的字体比标题的还要大,如何规范调整好文档正文的字体大小和格式
最新发布
07-30
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

昔人'

你的鼓励将是我创造的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值