栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Apache POI从Excel中获取HTML格式化的单元格值

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Apache POI从Excel中获取HTML格式化的单元格值

我将其作为unipre粘贴到xls文件的单元格A1中:

<html><p>This is a test. Will this text be <b>bold</b> or <i>italic</i></p></html>

此html行产生以下内容:

这是一个测验。该文字是 粗体 还是 斜体

我的代码:

public class ExcelWithHtml {    // <html><p>This is a test. Will this text be <b>bold</b> or    // <i>italic</i></p></html>    public static void main(String[] args) throws FileNotFoundException, IOException {        new ExcelWithHtml()     .readFirstCellOfXSSF("/Users/rcacheira/testeHtml.xlsx");    }    boolean inBold = false;    boolean inItalic = false;    public void readFirstCellOfXSSF(String filePathName) throws FileNotFoundException, IOException {        FileInputStream fis = new FileInputStream(filePathName);        XSSFWorkbook wb = new XSSFWorkbook(fis);        XSSFSheet sheet = wb.getSheetAt(0);        String cellHtml = getHtmlFormatedCellValueFromSheet(sheet, "A1");        System.out.println(cellHtml);        fis.close();    }    public String getHtmlFormatedCellValueFromSheet(XSSFSheet sheet, String cellName) {        CellReference cellReference = new CellReference(cellName);        XSSFRow row = sheet.getRow(cellReference.getRow());        XSSFCell cell = row.getCell(cellReference.getCol());        XSSFRichTextString cellText = cell.getRichStringCellValue();        String htmlCode = "";        // htmlCode = "<html>";        for (int i = 0; i < cellText.numFormattingRuns(); i++) { try {     htmlCode += getFormatFromFont(cellText.getFontAtIndex(i)); } catch (NullPointerException ex) { } try {     htmlCode += getFormatFromFont(cellText  .getFontOfFormattingRun(i)); } catch (NullPointerException ex) { } int indexStart = cellText.getIndexOfFormattingRun(i); int indexEnd = indexStart + cellText.getLengthOfFormattingRun(i); htmlCode += cellText.getString().substring(indexStart, indexEnd);        }        if (inItalic) { htmlCode += "</i>"; inItalic = false;        }        if (inBold) { htmlCode += "</b>"; inBold = false;        }        // htmlCode += "</html>";        return htmlCode;    }    private String getFormatFromFont(XSSFFont font) {        String formatHtmlCode = "";        if (font.getItalic() && !inItalic) { formatHtmlCode += "<i>"; inItalic = true;        } else if (!font.getItalic() && inItalic) { formatHtmlCode += "</i>"; inItalic = false;        }        if (font.getBold() && !inBold) { formatHtmlCode += "<b>"; inBold = true;        } else if (!font.getBold() && inBold) { formatHtmlCode += "</b>"; inBold = false;        }        return formatHtmlCode;    }}

我的输出:

This is a test. Will this text be <b>bold</b> or <i>italic</i>

我认为这就是您想要的,我只是向您展示可能性,我没有使用最佳代码实践,我只是在快速编程以产生输出。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/451441.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号