[英]HTML Formatted Cell value from Excel using Apache POI
我正在使用apache POI來閱讀excel文檔。 至少可以說,它至今可以滿足我的目的。 但是,我受到打擊的一件事是將單元格的值提取為HTML。
我有一個單元格,其中用戶將輸入一些字符串並應用一些格式(如子彈/數字/粗體/斜體)等。
因此,當我閱讀它時,內容應該是HTML格式,而不是POI給出的普通字符串格式。
我幾乎已經完成了整個POI API但卻無法找到任何人。 我想保留一個特定列的格式,而不是整個excel。 按列我的意思是,在該列中輸入的文本。 我希望該文本為HTML文本。
探索和使用Apache Tika也。 但據我所知它只能得到文本而不是文本的格式。
請有人指導我。 我的選項已經用完了。
假設我在Excel中寫了我的名字是天使和惡魔 。
我應該用Java獲得的輸出是My name is <b>Angel</b> and <i>Demon</i>
我將此作為unicode粘貼到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>
我認為這是你想要的,我只是告訴你可能性,我沒有使用最好的代碼實踐,我只是快速編程以產生輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.