去除<!--[if gte mso 9]......<![endif]-->字符串

去除Word自动生成代码
本文介绍了一种通过正则表达式匹配并删除Word文档中自动生成的特定代码的方法。这些代码通常用于保持文档的兼容性,但在某些情况下可能不需要它们。通过使用C#中的字符串替换功能,可以有效地移除这些标记。

复制word,去掉其中部分自动生成代码:

str=str.Replace(reg, "");

 string reg = @"/<!--\[if\s+gte\s+mso\s+9\]>(?:(?!<!\[endif\]-->)[\s\S])*<!\[endif\]-->/gi";



<p>
    <!--[if gte mso 9]

><xml><w:WordDocument><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery><w:DisplayVerticalDr

awingGridEvery>2</w:DisplayVerticalDrawingGridEvery><w:DocumentKind>DocumentNotSpecified</w:DocumentKind><w:DrawingGridVerticalSpacing>7.8 磅

</w:DrawingGridVerticalSpacing><w:PunctuationKerning></w:PunctuationKerning><w:View>Normal</w:View><w:Compatibility><w:DontGrowAutofit/><w:BalanceSingleByteDoubleByteWidth/><w:D

oNotExpandShiftReturn/><w:UseFELayout/></w:Compatibility><w:Zoom>0</w:Zoom></w:WordDocument></xml><![endif]--><!--[if gte mso 9]

><xml><w:WordDocument><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery><w:DisplayVerticalDr

awingGridEvery>2</w:DisplayVerticalDrawingGridEvery><w:DocumentKind>DocumentNotSpecified</w:DocumentKind><w:DrawingGridVerticalSpacing>7.8 磅

</w:DrawingGridVerticalSpacing><w:PunctuationKerning></w:PunctuationKerning><w:View>Normal</w:View><w:Compatibility><w:DontGrowAutofit/><w:BalanceSingleByteDoubleByteWidth/><w:D

oNotExpandShiftReturn/><w:UseFELayout/></w:Compatibility><w:Zoom>0</w:Zoom></w:WordDocument></xml><![endif]--></p>
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
<think>首先,用户的问题是:我想使用正则表达式提取特定注释标签之间的内容。请问正则表达式提取<!--[if gte vml1]>和<![endif]-->之间的内容。 我需要根据系统级指令来构建回答。指令包括: 1.行内数学表达式使用$...$格式,但用户的问题是关于正则表达式的,没有数学表达式,所以可能不需要。2.独立公式使用$$...$$格式,但同样,这里可能不适用。3.LaTeX语法正确,但在回答正则表达式时,我会使用代码块。4.使用中文回答。 5.生成相关问题。 6.回答中引用的段落末尾自然地添加引用标识,例如[^1]。用户提供的引用是: -引用[1]:关于JS函数去除特定标签的内容。 -引用[2]:关于Java正则表达式分组。-引用[3]:关于C#测试方法。 这些引用似乎与用户的问题相关,但用户说“上述引用仅供参考”,所以我应该参考这些引用,但聚焦于用户的问题。用户的问题是关于提取<!--[ifgtevml1]>和 <![endif]-->之间的内容。从引用[1],我看到一个函数:`ifGteVml(str)`,它使用`indexOf`来查找和替换内容。但用户想用正则表达式提取,而不是替换。 引用[2]讨论正则表达式分组,这很有用,因为提取内容可能需要分组。引用[3]是关于测试的,不太相关。 所以,我应该基于这些引用构建回答。 回答结构:-先理解用户需求:提取两个特定标签之间的内容。 -标签是:起始标签 `<!--[if gte vml1]>`和结束标签 `<![endif]-->`。-在正则表达式中,这些是固定字符串,所以我需要匹配它们之间的任何内容。正则表达式需要处理:-起始标签:`<!--[if gte vml1]>` -结束标签:`<![endif]-->` -之间的内容:任意字符,包括换行符,所以可能需要使用点号匹配所有字符,包括换行(使用`s`标志或`[\s\S]`)。在正则表达式中,`.`默认不匹配换行符,所以对于多行内容,需要使用`[\s\S]`或启用单行模式。 用户没有指定语言,但从引用看,JS、Java、C#都可能,所以我会给出通用的正则表达式。 正则表达式模式:`<!--\[if gte vml1\]>([\s\S]*?)<!\[endif\]-->` -`<!--\[if gte vml1\]>`:匹配起始标签。注意方括号需要转义,因为`[`和`]`在正则中是元字符。- `([\s\S]*?)`:匹配任何字符,包括换行,非贪婪模式,所以只匹配到第一个结束标签。 -`<!\[endif\]-->`:匹配结束标签。使用非贪婪`*?`确保只匹配到第一个结束标签,而不是贪婪匹配到最后一个。在代码中,提取内容时,需要捕获组。例如,在JavaScript中,可以使用`match`方法。 引用[1]中的函数使用了`indexOf`,但正则表达式更强大。 引用[2]解释了分组:group(0)是整个匹配,group(1)是第一个捕获组。所以,在正则表达式中,我会使用捕获组来提取内容。回答步骤: 1.解释正则表达式模式。 2.给出示例代码,基于引用(如JS或Java)。3.添加引用标识。 4.生成相关问题。 使用中文回答。 结构: -先介绍解决方案。 -然后给出正则表达式和解释。 -提供代码示例。 -添加引用。-最后生成相关问题。</think>### 正则表达式提取特定注释标签之间的内容 您的需求是使用正则表达式提取 `<!--[if gte vml 1]>` 和 `<![endif]-->` 之间的内容。这两个标签是 HTML 注释标签,常用于富文本或文档处理(如 Microsoft Word 生成的 HTML)。我将基于您提供的引用(特别是引用[1]和引用[2])来构建解决方案。正则表达式需要处理以下关键点: - 起始标签:`<!--[if gte vml 1]>`,其中方括号 `[` 和 `]` 是正则元字符,需要转义。 - 结束标签:`<![endif]-->`,同样需要转义方括号。 - 之间的内容:任意字符(包括换行符),需使用非贪婪匹配来避免过度匹配。 - 使用捕获组提取内容:正则表达式中,`group(0)` 匹配整个模式,`group(1)` 提取目标内容(参考引用[2])。 #### 正则表达式模式 通用的正则表达式模式为: ```regex <!--\[if gte vml 1\]>([\s\S]*?)<!\[endif\]--> ``` - **解释**: - `<!--\[if gte vml 1\]>`:匹配起始标签。`\[` 和 `\]` 转义方括号,确保正确匹配。 - `([\s\S]*?)`:捕获组(`()` 定义组),匹配任意字符(包括换行符)。`[\s\S]` 匹配空白和非空白字符(等价于“任何字符”),`*?` 表示非贪婪匹配(匹配到第一个结束标签即停止)。 - `<!\[endif\]-->`:匹配结束标签,同样转义方括号。 - 整个模式中,`group(1)` 将直接提取标签之间的内容(参考引用[2]中分组概念)。 #### 代码示例 以下示例基于不同编程语言(参考您提供的引用)。假设输入字符串是包含多个标签的富文本,例如: ```html Some text <!--[if gte vml 1]>Content to extract<![endif]--> more text. ``` - **JavaScript 示例**(参考引用[1]中的函数): JavaScript 中,使用 `match` 方法结合正则表达式提取内容。`match` 返回数组,索引 `1` 对应捕获组。 ```javascript function extractVmlContent(str) { const regex = /<!--\[if gte vml 1\]>([\s\S]*?)<!\[endif\]-->/; const match = str.match(regex); return match ? match[1] : null; // 返回提取的内容或 null } // 测试 const htmlString = &#39;Start <!--[if gte vml 1]>This is the target content.<![endif]--> End&#39;; const extracted = extractVmlContent(htmlString); console.log(extracted); // 输出: "This is the target content." ``` 此函数直接提取内容,避免了引用[1]中 `indexOf` 的繁琐处理[^1]。 - **Java 示例**(参考引用[2]中的正则分组): Java 中,使用 `Pattern` 和 `Matcher` 类。`group(1)` 获取捕获内容。 ```java import java.util.regex.Matcher; import java.util.regex.Pattern; public class VmlExtractor { public static String extract(String input) { Pattern pattern = Pattern.compile("<!--\\[if gte vml 1\\]>([\\s\\S]*?)<!\\[endif\\]-->"); Matcher matcher = pattern.matcher(input); if (matcher.find()) { return matcher.group(1); // 返回捕获组内容 } return null; } public static void main(String[] args) { String testString = "Prefix <!--[if gte vml 1]>Extract this text<![endif]--> Suffix"; String result = extract(testString); System.out.println(result); // 输出: "Extract this text" } } ``` 这里的分组机制与引用[2]一致:`group(0)` 是整个匹配字符串,`group(1)` 是目标内容[^2]。 #### 注意事项 - **性能与贪婪匹配**:使用非贪婪 `*?` 确保只提取第一个匹配项之间的内容。如果文本中有多个标签对,需使用全局匹配(如 JavaScript 的 `g` 标志)。 - **转义处理**:在编程语言中,正则字符串可能需要额外转义(如 Java 中的 `\\`)。 - **边界情况**:如果内容为空或标签缺失,代码应处理 `null` 结果。测试用例可参考引用[3]的单元测试方法[^3]。 - **通用性**:此模式适用于大多数语言(如 Python、C#),只需调整语法。 ### 相关问题 1. 如何处理正则表达式中的多行匹配和特殊字符转义? 2. 如果文档中有多个标签对,如何提取所有内容(全局匹配)? 3. 正则表达式在富文本处理中还有哪些常见应用场景? [^1]: 引用[1]展示了使用 `indexOf` 处理类似标签,但正则表达式更简洁高效。 [^2]: 引用[2]解释了正则分组,`group(1)` 直接对应捕获内容。 [^3]: 引用[3]强调了测试验证的重要性,确保提取逻辑正确。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值