I want to display some text with superscript into Excel cell. I tried to pass the HTML string to XSSFRichTextString but it displays the HTML string as it is in the output file.
I'm using Apache POI 3.16
You are thinking, RichTextString should be able to interpret HTML? It is not. It is only able to apply Font from startIndex
to endIndex
. And Font can be marked using TypeOffset SS_SUPER.
Example:
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import java.io.FileOutputStream;
class RichTextSuperscript {
public static void main(String[] args) {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
Font fontRed = wb.createFont();
fontRed.setColor(Font.COLOR_RED);
Font fontRedSuperscript = wb.createFont();
fontRedSuperscript.setColor(Font.COLOR_RED);
fontRedSuperscript.setTypeOffset(Font.SS_SUPER);
String string = "Level 3";
RichTextString richString = new XSSFRichTextString( "Level 13" );
//^0 ^7
richString.applyFont(7, 8, fontRedSuperscript);
for (int r = 0; r < 10; r++) {
Row row = sheet.createRow(r);
Cell cell = row.createCell(0);
if ((r%2) == 0) {
cell.setCellValue(string);
} else {
CellUtil.setFont(cell, fontRed);
cell.setCellValue(richString);
}
}
try {
wb.write(new FileOutputStream("RichTextSuperscript.xlsx"));
wb.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments