- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在从数据库获取 html 数据。下面是示例:
<ul>
<li> <strong>Iam Bold </strong> <u><span style="color:Red">Iam Red Colored and Underlined</span> </u> </li>
<li> Just a Normal Text </li>
<li> Iam <b> Bold </b> <i><span style="color:Green"> and italic with colored </span></i> <u> and underlined </u> </li>
</ul>
现在我的 Excel 输出中将出现相同的格式。Excel 输出请参见下图。
我知道通过使用 Jsoup ,您可以解析上面的 html,通过使用 XSSFRichTextString ,您可以在 xssfcell 中显示富文本。另外,通过使用项目符号字符,我可以获得项目符号图标。
但我需要输出中的完整文本。但我不知道如何准确地做到这一点以获得准确的输出。
如何使用 XSSFRichTextString 来做到这一点?请帮我解决这个问题
最佳答案
正如我在评论中所说,这将是一个棘手的实现。您需要创建一个解析器来解释 html 标记并将其应用为字体。下面的程序可以用作解析器的启动程序。它使用 jericho用于解析 html 的解析器并且具有有限的字体支持。然而它处理你给定的html(它可能能够以更好的方式实现这一点)。您还可以扩展它以获得额外的字体支持,例如删除线、字体大小等。您可以通过谷歌搜索各种字体实现。希望这会有所帮助。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
public class HtmlToExcel {
private static final int START_TAG = 0;
private static final int END_TAG = 1;
private static final char BULLET_CHARACTER = '\u2022';
private static final String NEW_LINE = System.getProperty("line.separator");
public static void main(String[] args) {
String html = "<ul>"
+ "<li><em><strong>Bold Non-Colored + <span style=\"color: #FF0000\">Bolded and Colored Text</span></strong> </em> + Non font trailing<br/></li>"
+ "<li>No Styling...Just a Text</li>"
+ "<li><u><b>Bolded </b> and <i>Italic </i> and Underlined Text</u></li>"
+ "<li><u>Underline Started and <span style=\"color: #00FF00\">Only Colored Text</span> Underline Ended</u></li>"
+ "</ul>";
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFSheet sheet = workBook.createSheet("Html Text");
Source source = new Source(html);
int cellNo = 0;
for (Element ul : source.getAllElements("ul")) {
List<RichTextDetails> cellValues = new ArrayList<HtmlToExcel.RichTextDetails>();
for (Element li : ul.getAllElements("li")) {
cellValues.add(createCellValue(li.toString(), workBook));
}
createCell(cellValues, workBook, sheet, cellNo++);
}
FileOutputStream out = null;
try {
out = new FileOutputStream(new File("C:\\new.xls"));
workBook.write(out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
private static void createCell(List<RichTextDetails> cellValues,
HSSFWorkbook workBook, HSSFSheet sheet, int cellNo) {
HSSFRichTextString cellValue = mergeTextDetails(cellValues);
HSSFCellStyle wrapStyle = workBook.createCellStyle();
wrapStyle.setWrapText(true);
Row row = sheet.createRow(cellNo);
Cell cell = row.createCell(0);
cell.setCellValue(cellValue);
}
private static HSSFRichTextString mergeTextDetails(
List<RichTextDetails> cellValues) {
StringBuilder textBuffer = new StringBuilder();
Map<Integer, HSSFFont> mergedMap = new LinkedHashMap<Integer, HSSFFont>();
int currentIndex = 0;
for(RichTextDetails richTextDetail : cellValues){
textBuffer.append(BULLET_CHARACTER + " ");
currentIndex = textBuffer.length();
for (Entry<Integer, HSSFFont> entry : richTextDetail.getFontMap().entrySet()) {
mergedMap.put(entry.getKey() + currentIndex, entry.getValue());
}
textBuffer.append(richTextDetail.getRichText()).append(NEW_LINE);
}
HSSFRichTextString richText = new HSSFRichTextString(textBuffer.toString());
for (int i = 0; i < textBuffer.length(); i++) {
HSSFFont currentFont = mergedMap.get(i);
if (currentFont != null) {
richText.applyFont(i, i + 1, currentFont);
}
}
return richText;
}
private static RichTextDetails createCellValue(String html, HSSFWorkbook workBook) {
Source source = new Source(html);
Map<String, TagInfo> tagMap = new LinkedHashMap<String, HtmlToExcel.TagInfo>();
for (Element e : source.getChildElements()) {
getInfo(e, tagMap);
}
String patternString = "(" + StringUtils.join(tagMap.keySet(), "|") + ")";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(html);
StringBuffer textBuffer = new StringBuffer();
List<RichTextInfo> textInfos = new ArrayList<HtmlToExcel.RichTextInfo>();
Stack<RichTextInfo> richTextBuffer = new Stack<HtmlToExcel.RichTextInfo>();
while (matcher.find()) {
matcher.appendReplacement(textBuffer, "");
TagInfo currentTag = tagMap.get(matcher.group(1));
if (START_TAG == currentTag.getTagType()) {
richTextBuffer.push(getRichTextInfo(currentTag, textBuffer.length(), workBook));
} else {
if (!richTextBuffer.isEmpty()) {
RichTextInfo info = richTextBuffer.pop();
if (info != null) {
info.setEndIndex(textBuffer.length());
textInfos.add(info);
}
}
}
}
matcher.appendTail(textBuffer);
Map<Integer, HSSFFont> fontMap = buildFontMap(textInfos, workBook);
return new RichTextDetails(textBuffer.toString(), fontMap);
}
private static Map<Integer, HSSFFont> buildFontMap(
List<RichTextInfo> textInfos, HSSFWorkbook workBook) {
Map<Integer, HSSFFont> fontMap = new LinkedHashMap<Integer, HSSFFont>();
for (RichTextInfo richTextInfo : textInfos) {
if (richTextInfo.isValid()) {
for (int i = richTextInfo.getStartIndex(); i < richTextInfo.getEndIndex(); i++) {
fontMap.put(i, mergeFont(fontMap.get(i), richTextInfo.getFontStyle(), richTextInfo.getFontValue(), workBook));
}
}
}
return fontMap;
}
private static HSSFFont mergeFont(HSSFFont font, STYLES fontStyle,
String fontValue, HSSFWorkbook workBook) {
if (font == null) {
font = workBook.createFont();
}
switch (fontStyle) {
case BOLD:
case EM:
case STRONG:
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
break;
case UNDERLINE:
font.setUnderline(HSSFFont.U_SINGLE);
break;
case ITALLICS:
font.setItalic(true);
break;
case COLOR:
if (!isEmpty(fontValue)) {
HSSFPalette palette = workBook.getCustomPalette();
HSSFColor myColor = palette.findSimilarColor(
Integer.valueOf(fontValue.substring(2, 4), 16),
Integer.valueOf(fontValue.substring(4, 6), 16),
Integer.valueOf(fontValue.substring(6, 8), 16));
font.setColor(myColor.getIndex());
}
break;
default:
break;
}
return font;
}
private static RichTextInfo getRichTextInfo(TagInfo currentTag,
int startIndex, HSSFWorkbook workBook) {
RichTextInfo info = null;
switch (STYLES.fromValue(currentTag.getTagName())) {
case SPAN:
if (!isEmpty(currentTag.getStyle())) {
for (String style : currentTag.getStyle().split(";")) {
String[] styleDetails = style.split(":");
if (styleDetails != null && styleDetails.length > 1) {
if ("COLOR".equalsIgnoreCase(styleDetails[0].trim())) {
info = new RichTextInfo(startIndex, -1, STYLES.COLOR, styleDetails[1]);
}
}
}
}
break;
default:
info = new RichTextInfo(startIndex, -1, STYLES.fromValue(currentTag.getTagName()));
break;
}
return info;
}
private static boolean isEmpty(String str) {
return (str == null || str.trim().length() == 0);
}
private static void getInfo(Element e, Map<String, HtmlToExcel.TagInfo> tagMap) {
tagMap.put(e.getStartTag().toString(), new TagInfo(e.getStartTag().getName(), e.getAttributeValue("style"), START_TAG));
if (e.getChildElements().size() > 0) {
List<Element> children = e.getChildElements();
for (Element child : children){
getInfo(child, tagMap);
}
}
if (e.getEndTag() != null) {
tagMap.put(e.getEndTag().toString(), new TagInfo(e.getEndTag().getName(), END_TAG));
} else {
// Handling self closing tags
tagMap.put(e.getStartTag().toString(), new TagInfo(e.getStartTag().getName(), END_TAG));
}
}
static class RichTextInfo {
private int startIndex;
private int endIndex;
private STYLES fontStyle;
private String fontValue;
public RichTextInfo(int startIndex, int endIndex, STYLES fontStyle) {
this.startIndex = startIndex;
this.endIndex = endIndex;
this.fontStyle = fontStyle;
}
public RichTextInfo(int startIndex, int endIndex, STYLES fontStyle,
String fontValue) {
this.startIndex = startIndex;
this.endIndex = endIndex;
this.fontStyle = fontStyle;
this.fontValue = fontValue;
}
public int getStartIndex() {
return startIndex;
}
public void setStartIndex(int startIndex) {
this.startIndex = startIndex;
}
public int getEndIndex() {
return endIndex;
}
public void setEndIndex(int endIndex) {
this.endIndex = endIndex;
}
public STYLES getFontStyle() {
return fontStyle;
}
public void setFontStyle(STYLES fontStyle) {
this.fontStyle = fontStyle;
}
public String getFontValue() {
return fontValue;
}
public void setFontValue(String fontValue) {
this.fontValue = fontValue;
}
public boolean isValid() {
return (startIndex != -1 && endIndex != -1 && endIndex >= startIndex);
}
@Override
public String toString() {
return "RichTextInfo [startIndex=" + startIndex + ", endIndex="
+ endIndex + ", fontStyle=" + fontStyle + ", fontValue="
+ fontValue + "]";
}
}
static class RichTextDetails {
private String richText;
private Map<Integer, HSSFFont> fontMap;
public RichTextDetails(String richText,
Map<Integer, HSSFFont> fontMap) {
this.richText = richText;
this.fontMap = fontMap;
}
public String getRichText() {
return richText;
}
public void setRichText(String richText) {
this.richText = richText;
}
public Map<Integer, HSSFFont> getFontMap() {
return fontMap;
}
public void setFontMap(Map<Integer, HSSFFont> fontMap) {
this.fontMap = fontMap;
}
}
static class TagInfo {
private String tagName;
private String style;
private int tagType;
public TagInfo(String tagName, String style, int tagType) {
this.tagName = tagName;
this.style = style;
this.tagType = tagType;
}
public TagInfo(String tagName, int tagType) {
this.tagName = tagName;
this.tagType = tagType;
}
public String getTagName() {
return tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
public int getTagType() {
return tagType;
}
public void setTagType(int tagType) {
this.tagType = tagType;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
@Override
public String toString() {
return "TagInfo [tagName=" + tagName + ", style=" + style
+ ", tagType=" + tagType + "]";
}
}
enum STYLES {
BOLD("b"),
EM("em"),
STRONG("strong"),
COLOR("color"),
UNDERLINE("u"),
SPAN("span"),
ITALLICS("i"),
UNKNOWN("unknown");
private String type;
private STYLES(String type) {
this.type = type;
}
public String getType() {
return type;
}
public static STYLES fromValue(String type) {
for (STYLES style : values()) {
if (style.type.equalsIgnoreCase(type)) {
return style;
}
}
return UNKNOWN;
}
}
}
关于java - 通过 XSSFRichTexString 和 Jsoup 格式化 Apache POI Excel 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24613916/
如何将扩展名为 ttf 和 otf 的新字体导入 POI API,而不将这些字体安装到环境中? Is there a jar that i should update it with the path
在这个问题的所有引用资料中,它没有解决并且不给maven因为没有在maven中做。错误是 包 org.apache.poi.ss.usermodel 可以从多个模块访问:poi、poi.ooxm在
上下文: 尝试使用 Apache POI 的 poi 和 poi-ooxml 4.0.0 版本 jar 打开 XLSX 文件 问题: 程序抛出错误,如下所示。当我使用 4.0.0 版本时,我发现此错误
刚开始使用 POI 3.10 创建 Word 文档(XWPF)。 大多数事情都是直截了当的,但我不明白如何添加页码。 我添加了页脚,但页脚中的文字在每一页上都相同 最佳答案 我在 LibreOffic
我正在使用 Apache POI 评估工作簿的每个公式单元格。当一个单元格包含对标准 excel 函数 NOW() 的调用时,Poi 会正确评估它并将调用替换为当前时间 - 格式为 VM 的默认时区。
我已经阅读了许多与我的要求相关的博客和论坛,但到目前为止,我能够在我得到的所有帮助下为第一级生成项目符号或编号。谁能指导我如何使用 apache poi 创建多级编号。 想知道 Apache POI
我正在使用 apache poi 创建 Excel 工作表。我有像 - 337499.939437217 这样的数字,我想在 Excel 中显示它,而不进行四舍五入。此外,单元格格式应为数字(对于某些
情况是,我合并了第一行的所有五个单元格,并在第一行的第一个单元格中插入了一个图像。我的要求是使图像在第一行水平居中。 我试过 cellStyle.setAlignment(CellStyle.ALIG
我正在尝试替换模板 DOCX使用 Apache 的文档 POI通过使用 XWPFDocument类(class)。我在文档中有标签和 JSON文件以读取替换数据。我的问题是 DOCX 中的文本行似乎以
好吧,老实说:标题并没有说出全部真相。我正在使用带有多个按钮(保存、关闭、编辑等)和一个执行 POI 操作的按钮的自定义控件 - 它生成一个 Word 文件。 我在这里遇到一个问题:点击 POI 按钮
有什么方法可以让我获得 excel 连续显示的格式化值,而不是我从流中返回的原始值? 或者这是否属于“公式评估”类别,这不支持? 最佳答案 如果您有 Cell您正在尝试从中获取数据,请尝试以下操作 D
在 xlsx 工作簿中,有一些单元格带有一些无界 SUMIF 公式,如下所示:SUMIF(MySheetname!$B:$B,$E4,MySheetname!$I:$I) . 使用 Apache PO
我正在创建一个 Java 程序来读取 Excel 工作表并创建一个逗号分隔的文件。当我运行带有空白列的示例 excel 文件时,第一行工作正常,但其余行跳过空白单元格。 我已经阅读了将空白单元格插入行
我目前正在使用 POI 使用 XSLF 编辑 PPTX 文件内嵌入图表中的数据。我找到了一个使用带有饼图的模板 ppt 的示例,效果非常好。我还尝试编辑折线图并且它有效。但是,当我尝试编辑嵌入式条形图
我正在学习使用 Selenium 和 Excel 进行数据驱动测试。我正在参加一门在线类(class),要求在 Maven 中添加 Apache poi 和 poi-ooxml 依赖项。 我正在努力理
我们有一个具有画廊功能的应用程序,我们想将图像导出到 powerpoint 演示文稿中。我能够做到这一点,但由于图像的大小和方向不同,图像边界几乎总是超出 ppt 幻灯片。我如何调整图像的大小(我不想
我有一个带有以下幻灯片布局的 pptx: System.out.println("Available slide layouts:"); for(XSLFSlideMaster master
我正在尝试使用 Java 中的 POI api 创建 Excel 工作表。在那个 Excel 工作表中,我想要一个只有 TIME 的单元格。通过设置它,我们可以像在数字列中那样将单元格包含在该特定列的
Apache Poi 可以计算和返回公式中函数的结果。但是对于特殊函数 HYPERLINK(),它只返回“显示值”,而不是实际计算的超链接值。 我有一个 Excel 文件,其中包含复杂的计算超链接,这
我正在使用 Apache POI。 我可以使用“org.apache.poi.hwpf.extractor.WordExtractor”从文档文件中读取文本 甚至使用“org.apache.poi.h
我是一名优秀的程序员,十分优秀!