POI richText和html的转换案例
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的转换案例的更多相关文章
- POI生成word文档完整案例及讲解
一,网上的API讲解 其实POI的生成Word文档的规则就是先把获取到的数据转成xml格式的数据,然后通过xpath解析表单式的应用取值,判断等等,然后在把取到的值放到word文档中,最后在输出来. ...
- poi解析word文档转换成html(包括图片解析)
需求:将本地上传的word文档解析并放入数据库中 代码: import java.io.ByteArrayOutputStream;import java.io.File;import java.io ...
- 【学亮IT手记】MySql行列转换案例
create table score( name ), math int, english int ); ,); ,); ,); ,); SHOW tables; SELECT * from scor ...
- kettle——转换案例
把stu1的数据按id同步到stu2,stu2有相同id则更新数据 (1)在mysql中创建两张表 mysql> create database kettle; mysql> use ke ...
- java poi Excel导入 整数浮点数转换问题解决
/** * 获取单元格数据 */ protected static String getCellValue(Cell cell) { String cellValu ...
- C# 数组与 list 互相转换案例
在项目中用到了 随手分享下 记得点赞呦! 1,从System.String[]转到List<System.String>System.String[] str={"str&quo ...
- poi导出excel
Java使用poi组件导出excel报表,能导出excel报表的还可以使用jxl组件,但jxl想对于poi功能有限,jxl应该不能载excel插入浮动层图片,poi能很好的实现输出excel各种功能, ...
- 关于html转换为pdf案例的一些测试与思考
由于工作所需,最近花时间研究了html转换为pdf的功能.html转换为pdf的关键技术是如何处理网页中复杂的css样式,通过在网上收集资料,发现目前html 转换为pdf的解决方案主要分为三类: 客 ...
- Java基础-处理json字符串解析案例
Java基础-处理json字符串解析案例 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 作为一名开发人员,想必大家或多或少都有接触到XML文件,XML全称为“extensible ...
随机推荐
- 关于Error during managed flush [Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1]错误
控制台报错: 08:07:09.293 [http-bio-8080-exec-2] ERROR org.hibernate.internal.SessionImpl - HHH000346: Err ...
- ADO.NET 的五个对象
首先来一张关系图,了解大概关系. 知道了整个大关系之后,我们在具体看一下他们五个的分工: 1. SqlConnection 在访问数据时,我们首先必须要建立数据库的物理连接.· 2.SqlComman ...
- APPicon的生成
APPIcon 工厂图标的生成:http://icon.wuruihong.com/#/home
- Windows CMD 支持ls命令
/********************************************************************** * Windows CMD 支持ls命令 * 说明: * ...
- Centos上SSH连接过慢原因
最近发现机房里有些centos机器进行ssh登陆非常慢且会超时,经过查看发现时GSPI认证过慢问题造成: 使用 ssh -v 发现 debug1: SSH2_MSG_SERVICE_ACCEPT re ...
- 查看Linux磁盘空间
df -hl 查看磁盘剩余空间 df -h 查看每个根路径的分区大小 du -sh [目录名] 返回该目录的大小 du -sm [文件夹] 返回该文件夹总M数 du -h [目录名] 查看指定文件夹下 ...
- js中的Call()和apply()
Call和apply,就是改变函数里面的this指向的方法. xxx.call()或xxx.apply() 特别强调下xxx必须是function,(普通函数,类,构造函数) var obj={ na ...
- VS2015 使用 Visual Studio Emulator For Android 调试无法命中断点的解决办法?
源解决方案是英文版的,地址:https://dzone.com/articles/fix-for-could-not-connect-to-the-debugger-while-de 问题现象: 1. ...
- spotlight工具监控oracle
spotlight工具版本Version: 5.0.1.1022 安装步骤 安装完成 安装之后,桌面上会生成如下图标 双机此图标,输入License 输入激活码 点击close,再次查看 建立连接,监 ...
- 集合总结三(HashMap的实现原理)
一.概述 二话不说,一上来就点开源码,发现里面有一段介绍如下: Hash table based implementation of the Map interface. This implement ...