private XSSFRichTextString parseHtmlStrToRichText(String htmlStr) {
Document document = parseHtmlStrToDocument(htmlStr);
XSSFRichTextString rts = parseDocementToRichText(document.getChildNodes().item(0));
return rts;
}
private Document parseHtmlStrToDocument(String content){ content = "<content>" + content + "</content>";
    
     //html的换行标签变为excel的换行
content = content.replaceAll("<br/>", "\n"); DocumentBuilderFactory documentbuilderfactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder;
Document document = null;
try {
documentBuilder = documentbuilderfactory.newDocumentBuilder();
document = documentBuilder.parse(new ByteArrayInputStream(content.getBytes("UTF-8"))); } catch (Exception e) {
e.printStackTrace();
}
return document;
}
private XSSFRichTextString parseDocementToRichText(Node contentNode) {
String wholeTextContent = contentNode.getTextContent();
XSSFRichTextString rts = new XSSFRichTextString(); rts.append(wholeTextContent);
setRichText(rts, contentNode, 0, null);
return rts;
}
private void setRichText(RichTextString rts, Node contentNode, int startIndex, XSSFFont parentFont) {
if (contentNode.getNodeType() == Node.TEXT_NODE) {
return;
} else {
String textContent = contentNode.getTextContent(); XSSFFont font = null;
if (!contentNode.getNodeName().equals("content")) {
font = getRichTextFontOfNode(contentNode, parentFont);
rts.applyFont(startIndex, startIndex + textContent.length(), font);
} NodeList nodeList = contentNode.getChildNodes();
int fontLength = startIndex;
String subTextContent = "";
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
subTextContent = node.getTextContent(); if (node.getNodeType() == Node.TEXT_NODE) {
} else {
setRichText(rts, node, fontLength, font);
}
fontLength += subTextContent.length();
}
} } private XSSFFont getRichTextFontOfNode(Node node, XSSFFont parentFont) { XSSFFont font = new XSSFFont();
font.setFontName(FONT_NAME);
font.setFontHeightInPoints(RICH_FONT_SIZE_DEFAULT);
short fontHeight = RICH_FONT_SIZE_DEFAULT;
if (parentFont != null) {
fontHeight = parentFont.getFontHeightInPoints();
font.setFontHeightInPoints(fontHeight);
font.setColor(parentFont.getXSSFColor());
font.setBold(parentFont.getBold());
font.setUnderline(parentFont.getUnderline());
} if ("span".equals(node.getNodeName())) {
String className = node.getAttributes().getNamedItem("class").getNodeValue();
switch(className) {
case RICH_CSS_01: {
font.setBold(true);
break;
}
case RICH_CSS_02: {
font.setUnderline(XSSFFont.U_SINGLE);
break;
}
case RICH_CSS_03: {
font.setFontHeightInPoints(RICH_FONT_SIZE_3);
font.setBold(true);
break;
}
case RICH_CSS_04: {
int[] rgbColor = P2StringUtil.hexToRgb(RICH_ARGB_BLACK);
XSSFColor xssfColor = new XSSFColor(new java.awt.Color(rgbColor[0], rgbColor[1], rgbColor[2]), new DefaultIndexedColorMap());
font.setColor(xssfColor);
break;
}
case RICH_CSS_05: {
int[] rgbColor = P2StringUtil.hexToRgb(RICH_ARGB_RED);
XSSFColor xssfColor = new XSSFColor(new java.awt.Color(rgbColor[0], rgbColor[1], rgbColor[2]), new DefaultIndexedColorMap());
font.setColor(xssfColor);
break;
}
case RICH_CSS_06: {
int[] rgbColor = P2StringUtil.hexToRgb(RICH_ARGB_BLUE);
XSSFColor xssfColor = new XSSFColor(new java.awt.Color(rgbColor[0], rgbColor[1], rgbColor[2]), new DefaultIndexedColorMap());
font.setColor(xssfColor);
break;
}
}
} else if ("font".equals(node.getNodeName())) {
int fontSize = Integer.parseInt(node.getAttributes().getNamedItem("size").getNodeValue()); switch(fontSize) {
case 1:
fontHeight = RICH_FONT_SIZE_1;
break;
case 2:
fontHeight = RICH_FONT_SIZE_2;
break;
case 3:
fontHeight = RICH_FONT_SIZE_3;
break;
case 4:
fontHeight = RICH_FONT_SIZE_4;
break;
case 5:
fontHeight = RICH_FONT_SIZE_5;
break;
case 6:
fontHeight = RICH_FONT_SIZE_6;
break;
default:
fontHeight = RICH_FONT_SIZE_7;
break;
}
font.setFontHeightInPoints(fontHeight); } return font;
} private String parseRichTextToHtmlStr(XSSFCell cell) {
String htmlStr = ""; String cellType = cell.getCellType().toString();
if (!"STRING".equals(cellType)) {
htmlStr = InstructionUtil.getCellValueByCell(cell);
return htmlStr;
}
XSSFRichTextString rts = cell.getRichStringCellValue();
String wholeContentText = rts.getString();
if (StringUtils.isEmpty(wholeContentText)) {
return wholeContentText;
}
if (rts.numFormattingRuns() == 0) {
XSSFCellStyle cellStyle = cell.getCellStyle();
XSSFFont font = cellStyle.getFont(); htmlStr = parseFontToHtmlStr(font, wholeContentText);
} else {
for(int i=0; i<rts.numFormattingRuns(); i++) {
String subContent = wholeContentText.substring(rts.getIndexOfFormattingRun(i), rts.getIndexOfFormattingRun(i)+rts.getLengthOfFormattingRun(i));
XSSFFont font = rts.getFontAtIndex(rts.getIndexOfFormattingRun(i));
if (!"".equals(subContent)) {
htmlStr += parseFontToHtmlStr(font, subContent);
} }
} return htmlStr;
} private String parseFontToHtmlStr (XSSFFont font, String contentText) {
String htmlStr = "";
StringBuffer sb = new StringBuffer();
XSSFColor color = font.getXSSFColor();
String colorClass = null;
boolean underlined = false;
boolean isBold = font.getBold();
if (color != null && color.getARGBHex() != null) {
switch (color.getARGBHex()) {
case RICH_ARGB_BLACK:
colorClass = RICH_CSS_04;
break;
case RICH_ARGB_RED:
colorClass = RICH_CSS_05;
break;
case RICH_ARGB_BLUE:
colorClass = RICH_CSS_06;
break;
}
}
if (Font.U_SINGLE == font.getUnderline()) {
underlined = true;
} short fontHeight = font.getFontHeightInPoints();
short fontSize = 3;
boolean isDefaultFontSize = false;
if (fontHeight <= RICH_FONT_SIZE_1) {
fontSize = 1;
} else if( fontHeight == RICH_FONT_SIZE_DEFAULT) {
isDefaultFontSize = true;
} else if(fontHeight <= RICH_FONT_SIZE_2) {
fontSize = 2;
} else if(fontHeight<= RICH_FONT_SIZE_3) {
fontSize = 3;
} else if(fontHeight<=RICH_FONT_SIZE_4) {
fontSize = 4;
} else if(fontHeight<=RICH_FONT_SIZE_5) {
fontSize = 5;
} else if(fontHeight<=RICH_FONT_SIZE_6) {
fontSize = 6;
} else {
fontSize = 7;
} if (colorClass != null) {
sb.append("<span class=\"" + colorClass+ "\">");
}
if (underlined) {
sb.append("<span class=\"" + RICH_CSS_02+ "\">");
}
if (isBold) {
sb.append("<span class=\"" + RICH_CSS_01+ "\">");
}
if (!isDefaultFontSize) {
sb.append("<font size=\"" + fontSize + "\">");
} //excelの値の特殊文字(例:<span></span>など)をescape
contentText = StringEscapeUtils.escapeXml11(contentText);
sb.append(contentText);
if (!isDefaultFontSize) {
sb.append("</font>");
} if (isBold) {
sb.append("</span>");
}
if (underlined) {
sb.append("</span>");
}
if (colorClass != null) {
sb.append("</span>");
} htmlStr = sb.toString();
htmlStr = htmlStr.replaceAll("\\R", "<br/>");
return htmlStr;
}

POI richText和html的转换案例的更多相关文章

  1. POI生成word文档完整案例及讲解

    一,网上的API讲解 其实POI的生成Word文档的规则就是先把获取到的数据转成xml格式的数据,然后通过xpath解析表单式的应用取值,判断等等,然后在把取到的值放到word文档中,最后在输出来. ...

  2. poi解析word文档转换成html(包括图片解析)

    需求:将本地上传的word文档解析并放入数据库中 代码: import java.io.ByteArrayOutputStream;import java.io.File;import java.io ...

  3. 【学亮IT手记】MySql行列转换案例

    create table score( name ), math int, english int ); ,); ,); ,); ,); SHOW tables; SELECT * from scor ...

  4. kettle——转换案例

    把stu1的数据按id同步到stu2,stu2有相同id则更新数据 (1)在mysql中创建两张表 mysql> create database kettle; mysql> use ke ...

  5. java poi Excel导入 整数浮点数转换问题解决

    /**     * 获取单元格数据     */    protected static String getCellValue(Cell cell) {        String cellValu ...

  6. C# 数组与 list 互相转换案例

    在项目中用到了 随手分享下 记得点赞呦! 1,从System.String[]转到List<System.String>System.String[] str={"str&quo ...

  7. poi导出excel

    Java使用poi组件导出excel报表,能导出excel报表的还可以使用jxl组件,但jxl想对于poi功能有限,jxl应该不能载excel插入浮动层图片,poi能很好的实现输出excel各种功能, ...

  8. 关于html转换为pdf案例的一些测试与思考

    由于工作所需,最近花时间研究了html转换为pdf的功能.html转换为pdf的关键技术是如何处理网页中复杂的css样式,通过在网上收集资料,发现目前html 转换为pdf的解决方案主要分为三类: 客 ...

  9. Java基础-处理json字符串解析案例

    Java基础-处理json字符串解析案例 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 作为一名开发人员,想必大家或多或少都有接触到XML文件,XML全称为“extensible ...

随机推荐

  1. SQL注入之Sqli-labs系列第三十三关(基于宽字符逃逸注入)

    开始挑战第三十三关(Bypass addslashes) 0x1查看源码 本关和第三十二关其实是一样的,只是这里用到了addslashes()函数 function check_addslashes( ...

  2. 2017《JAVA技术》预备作业-计科1502-19-何俏依

    1.阅读邹欣老师的博客,谈谈你期望的师生关系是什么样的? 我期望的师生关系是长辈和晚辈,前辈和后生,朋友与朋友之间的关系,作为晚辈,要尊敬长辈,不能对长辈进行言语攻击和起冲突:作为后生,要谨遵教诲,有 ...

  3. Codeforces 1080C- Masha and two friends

    AC代码 #include <bits/stdc++.h> #define ll long long const int maxn=1e6+10; using namespace std; ...

  4. ViewpageAdapter

    import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory; ...

  5. Arch Linux 的休眠设置

    https://wiki.archlinux.org/index.php/Power_management/Suspend_and_hibernate_(简体中文)https://wiki.archl ...

  6. Cronolog切割tomcat日志

    Cronolog切割tomcat 安装cronolog 1. 将cronolog-1.6.2.tar.gz 上传至/opt 目录 2. 解压缩 #解压缩 tar -zxvf cronolog-1.6. ...

  7. mac下pycharm快捷键

    [转载]https://www.cnblogs.com/leolichao/p/9329685.html Mac键盘符号和修饰键说明 ⌘ Command ⇧ Shift ⌥ Option ⌃ Cont ...

  8. [Android]-图片JNI(C++\Java)高斯模糊的实现与比較

    版权声明:本文作者:Qiujuer https://github.com/qiujuer; 转载请注明出处,盗版必究! !! https://blog.csdn.net/qiujuer/article ...

  9. day45 jQuery

    在用js写代码时,会遇到一些问题: window.onload 事件有事件覆盖的问题,因此只能写一个事件. 代码容错性差. 浏览器兼容性问题. 书写很繁琐,代码量多. 代码很乱,各个页面到处都是. 动 ...

  10. debian系统下apache2开启ssi功能

    SSI (Server Side Include)的 html 文件扩展名 (.shtml), 通常称为"服务器端嵌入"或者叫"服务器端包含"说白了就是类似其他 ...