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

本文介绍了一种优化方法,用于移除HTML中的IE条件注释,通过增强通用性和灵活性来提高代码效率。

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

如下代碼可以进行优化

 
/**
 * 清除文本中的ie注释
 * @param content
 * @return
 */
public static String removeIENotes(String content) {
    if(StringUtils.isNotNull(content)) {
        if(content.contains("<![endif]-->")) {
            content = content.substring(content.lastIndexOf("<![endif]-->")+12,content.length());
        }
    }
    return content;

}

 

改良后:提共通,content是前台传过来的字符串,str是包含特殊字符的字符串。

 

public static String removeIENotes(String content,String str) {
    if(StringUtils.isNotNull(content)) {
        if(content.contains(str)) {
            content = content.substring(content.lastIndexOf(str)+str.length(),content.length());
        }
    }
    return content;

}

 

 

 

 

采用此方法在Java端insert,或者update方法中使用,具体如下例子:

String str = "<!--[if gte mso 9]><xml> <o:OfficeDocumentSettings>  <o:RelyOnVML/>  <o:AllowPNG/> </o:OfficeDocumentSettings></xml><![endif]--><!--[if gte mso 9]><xml> ...

...

...

...

...

...

...</xml><![endif]--><!--[if gte mso 10]><style> /* Style Definitions */ table.MsoNormalTable{mso-style-name:普通表格;mso-tstyle-rowband-size:0;mso-tstyle-colband-size:0;mso-style-noshow:yes;mso-style-priority:99;mso-style-parent:"";mso-padding-alt:0cm 5.4pt 0cm 5.4pt;mso-para-margin:0cm;mso-para-margin-bottom:.0001pt;mso-pagination:widow-orphan;font-size:10.5pt;mso-bidi-font-size:11.0pt;font-family:"Arial",sans-serif;mso-ascii-font-family:Arial;mso-ascii-theme-font:minor-latin;mso-hansi-font-family:Arial;mso-hansi-theme-font:minor-latin;mso-bidi-font-family:"Times New Roman";mso-bidi-theme-font:minor-bidi;mso-font-kerning:1.0pt;}</style><![endif]--><span style="mso-bidi-font-size:10.5pt;font-family:&quot;微软雅黑&quot;,sans-serif">近年来,随着世界经济一体化的日益加深,众多跨国企业在华投资,我国大型企业也走出国门在海外投资设厂,无论是政府税务机关还是企业集团总部都不可避免地面临转让定价的问题。关联交易中的转让定价对于集团总部来说是战略行为,对于政府税务机关来说则是税收安全问题。因此,构建符合实际情况的预约定价申请事十分必要的。<span lang="EN-US"></span></span>"

aaa.setFileName(removeIENotes(str));

@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&lt;=0){ log.warn("没有选择需要生成word文档的数据,不作处理,返回。"); return; } // 是否导出备注详情 int notesExportFlag = articleData.getNotesExportFlag(); // 导出数据准备---------------------------------- List&lt;ArticleData&gt; articleDataList = articleDataMapper.selectArticleDataByIds(ids); if (articleDataList==null || articleDataList.size()&lt;=0){ log.warn("获取的word文档数据为空,不作处理,返回。"); return; } // 批量获取模块数据 ,然后进行排序======================================= // Long[] menu_ids = new Long[articleDataList.size()]; // for(int i=0;i&lt;articleDataList.size();i++){ // menu_ids[i] = articleDataList.get(i).getMenuId(); // } // List&lt;ArticleMenu&gt; menu_list = articleMenuMapper.selectArticleMenuByMenuIds(menu_ids); // // 排序 // Collections.sort(menu_list, new Comparator&lt;ArticleMenu&gt;() { // @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&lt;Integer,Map&lt;Long, Map&lt;Long, List&lt;Map&lt;String, Object&gt;&gt;&gt;&gt;&gt; myDatasMap = new HashMap&lt;Integer,Map&lt;Long, Map&lt;Long, List&lt;Map&lt;String, Object&gt;&gt;&gt;&gt;&gt;(); //菜单最深层数 int maxLevel = 1; // 菜单纵信息 List&lt;Long[]&gt; list_coloum = new ArrayList&lt;Long[]&gt;(); // 菜单纵信息及后面按显示顺序排序 List&lt;String[]&gt; list_coloum_str = new ArrayList&lt;String[]&gt;(); // 获取模块目录信息 for(ArticleData param : articleDataList){ //这里导出的时候加上备注的内容 if(notesExportFlag&gt;0 && StringUtils.isNotBlank(param.getNotes())){ param.setContent(param.getContent() +"&lt;p&gt;&lt;br/&gt;&lt;/p&gt;" +"&lt;p&gt;***备注***:&lt;/p&gt;" +"&lt;p&gt;"+param.getNotes()+"&lt;/p&gt;"); } 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&gt;0){ for(int i=0;i&lt;menuIdArr.length;i++){ menuIdsArr[i] = Long.parseLong(menuIdArr[i].trim()); if(i&gt;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()&gt;0){ String resourcePath = System.getProperty("user.dir") + "/src/main/resources/"; log.info("项目resource路径 resourcePath:"+resourcePath); List&lt;Map&lt;String, Object&gt;&gt; dataList = new ArrayList&lt;Map&lt;String, Object&gt;&gt;(); StringBuffer titleSb = new StringBuffer(); // 存放已经遍历到并处理的模块ID List&lt;Long&gt; menus_handled = new ArrayList&lt;Long&gt;(); // 记录多于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&lt;Long[]&gt;() { // @Override // public int compare(Long[] o1, Long[] o2) { // // TODO Auto-generated method stub // int flag = 0; // int len = o1.length&gt;o2.length?o2.length:o1.length; // for(int i=0;i&lt;len;i++){ // int diff = (int) (o1[i]-o2[i]); // flag = flag+diff; // } // return flag; // } // }); //按显示顺序升序排序list_coloum_str Collections.sort(list_coloum_str, new Comparator&lt;String[]&gt;() { @Override public int compare(String[] o1, String[] o2) { // TODO Auto-generated method stub int flag = 0; int len = o1.length&gt;o2.length?o2.length:o1.length; for(int i=1;i&lt;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&lt;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&lt;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()&gt;0){ for(Long menuid_handled : menus_handled){ if(menuid_handled.equals(current_menu_id)){ // 已处理的,就跳过 continue mu; } } } //层级、menuId(现为父类模块ID)、排序order_num(注?:确保排序唯一) Map&lt;Long, Map&lt;Long, List&lt;Map&lt;String, Object&gt;&gt;&gt;&gt; current_menu = myDatasMap.get(i); if(current_menu!=null && current_menu.size()&gt;0){ List&lt;Long&gt; contentMenuIdsExist = new ArrayList&lt;Long&gt;(); for(Long current_parent_id : current_menu.keySet()){ Map&lt;Long, List&lt;Map&lt;String, Object&gt;&gt;&gt; current_parent_map = current_menu.get(current_parent_id); if(current_parent_map!=null && current_parent_map.size()&gt;0){ for(Long current_order_num : current_parent_map.keySet()){ List&lt;Map&lt;String, Object&gt;&gt; current_order_list = current_parent_map.get(current_order_num); if(current_order_list!=null && current_order_list.size()&gt;0){ for(Map&lt;String, Object&gt; 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&gt;0 &&current_level_order&lt;max_level_content ))){ //说明该模块只有一个,这里作为标题 if(max_level_content&gt;0){ if(current_level_order&lt;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()&gt;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&lt;1?1:current_level-max_level; if(current_level&gt;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&lt;String, Object&gt; wordData = new HashMap&lt;&gt;(); wordData.put("directory", title_num+" "+current_order_map.get("menuName")); Map&lt;String, Object&gt; wordDataMap = new HashMap&lt;&gt;(); 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&lt;1?1:current_level-max_level+1; if(current_level&gt;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&lt;String, Object&gt; wordData = new HashMap&lt;&gt;(); wordData.put("directory", " "+title_num+" "+current_article_data.getTitle()); Map&lt;String, Object&gt; wordDataMap = new HashMap&lt;&gt;(); //int current_level = (int) current_order_map.get("menuLevel"); //int level = current_level-max_level&lt;1?1:current_level-max_level; wordDataMap.put("templateParth", resourcePath+"templates/bms_menu"+level+".docx"); wordDataMap.put("wordData", wordData); dataList.add(wordDataMap); // 内容 Map&lt;String, Object&gt; theData = new HashMap&lt;&gt;(); //=================================================================== // 测试内容 &lt;p&gt;&lt;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" /&gt;&lt;/p&gt; // 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 = "&lt;p&gt;&lt;img src=\""+base64+"\" alt=\"\" width=\"872\" height=\"436\" /&gt;&lt;/p&gt;"; //==================================================================== ////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 // :"&lt;span style=\"color: red;\"&gt;~标题为:"+current_article_data.getTitle()+"(id="+current_article_data.getId()+")的内容为空&lt;/span&gt;"); //针对内容的处理,主要是导出的时候图片的问题 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&lt;String&gt; imgValues = PoiWordUtil.getTagAttributeValues(current_article_data.getContent(), "img", "src"); if(imgValues!=null && imgValues.size()&gt;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&gt;=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 = "&lt;span style=\"color: red;\"&gt;~标题为:"+current_article_data.getTitle()+"(id="+current_article_data.getId()+")的内容为空&lt;/span&gt;"; } theData.put("content", content); Map&lt;String, Object&gt; wordDataMap2 = new HashMap&lt;&gt;(); 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&lt;String, Object&gt; wordHead_test = new HashMap&lt;&gt;(); wordHead_test.put("title", titleSb.substring(0, titleSb.length()-1)); wordHead_test.put("currentTime", DateUtils2.getCurrentDateTime()); //首页数据 Map&lt;String, Object&gt; wordHeadMap_test = new HashMap&lt;&gt;(); 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&lt;String, Object&gt; headMap,List&lt;Map&lt;String, Object&gt;&gt; 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&lt;String, Object&gt; wordData_head = headMap.get("wordData")!=null?(Map&lt;String, Object&gt;) 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()&lt;=0){ log.warn("模块数据为空,不作解析导出"); return; } try { //多文档集合 List&lt;NiceXWPFDocument&gt; list = new ArrayList&lt;NiceXWPFDocument&gt;(); 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&lt;String, Object&gt; dataMap : dataList){ String templateParth_data = dataMap.get("templateParth")!=null?String.valueOf(dataMap.get("templateParth")).trim():""; Map&lt;String, Object&gt; wordData_data = dataMap.get("wordData")!=null?(Map&lt;String, Object&gt;) 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("&lt;", "&lt;").replace("&gt;", "&gt;").replace(""", "\"").replace("&", "&"); // 拼接html格式内容 StringBuffer sbf = new StringBuffer(); // 这里拼接一下html标签,便于word文档能够识别 sbf.append("&lt;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版式改成页面试图 "&gt;"); sbf.append("&lt;head&gt;" + "&lt;!--[if gte mso 9]&gt;&lt;xml&gt;&lt;w:WordDocument&gt;&lt;w:View&gt;Print&lt;/w:View&gt;&lt;w:TrackMoves&gt;false&lt;/w:TrackMoves&gt;&lt;w:TrackFormatting/&gt;&lt;w:ValidateAgainstSchemas/&gt;&lt;w:SaveIfXMLInvalid&gt;false&lt;/w:SaveIfXMLInvalid&gt;&lt;w:IgnoreMixedContent&gt;false&lt;/w:IgnoreMixedContent&gt;&lt;w:AlwaysShowPlaceholderText&gt;false&lt;/w:AlwaysShowPlaceholderText&gt;&lt;w:DoNotPromoteQF/&gt;&lt;w:LidThemeOther&gt;EN-US&lt;/w:LidThemeOther&gt;&lt;w:LidThemeAsian&gt;ZH-CN&lt;/w:LidThemeAsian&gt;&lt;w:LidThemeComplexScript&gt;X-NONE&lt;/w:LidThemeComplexScript&gt;&lt;w:Compatibility&gt;&lt;w:BreakWrappedTables/&gt;&lt;w:SnapToGridInCell/&gt;&lt;w:WrapTextWithPunct/&gt;&lt;w:UseAsianBreakRules/&gt;&lt;w:DontGrowAutofit/&gt;&lt;w:SplitPgBreakAndParaMark/&gt;&lt;w:DontVertAlignCellWithSp/&gt;&lt;w:DontBreakConstrainedForcedTables/&gt;&lt;w:DontVertAlignInTxbx/&gt;&lt;w:Word11KerningPairs/&gt;&lt;w:CachedColBalance/&gt;&lt;w:UseFELayout/&gt;&lt;/w:Compatibility&gt;&lt;w:BrowserLevel&gt;MicrosoftInternetExplorer4&lt;/w:BrowserLevel&gt;&lt;m:mathPr&gt;&lt;m:mathFont m:val=\"Cambria Math\"/&gt;&lt;m:brkBin m:val=\"before\"/&gt;&lt;m:brkBinSub m:val=\"--\"/&gt;&lt;m:smallFrac m:val=\"off\"/&gt;&lt;m:dispDef/&gt;&lt;m:lMargin m:val=\"0\"/&gt; &lt;m:rMargin m:val=\"0\"/&gt;&lt;m:defJc m:val=\"centerGroup\"/&gt;&lt;m:wrapIndent m:val=\"1440\"/&gt;&lt;m:intLim m:val=\"subSup\"/&gt;&lt;m:naryLim m:val=\"undOvr\"/&gt;&lt;/m:mathPr&gt;&lt;/w:WordDocument&gt;&lt;/xml&gt;&lt;![endif]--&gt;" + "&lt;/head&gt;"); sbf.append("&lt;body&gt;"); // 富文本内容 sbf.append(tmpContent); sbf.append("&lt;/body&gt;&lt;/html&gt;"); HtmlRenderPolicy htmlRenderPolicy1 = new HtmlRenderPolicy(); Configure configure1 = Configure.builder() .bind("content", htmlRenderPolicy1) .build(); Map&lt;String, Object&gt; data1 = new HashMap&lt;&gt;(); 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值