如何使用Apache POI添加上标文本

时间:2017-06-05 14:52:26

标签: apache-poi

我想在Excel单元格中显示带有上标的文本。我试图将HTML字符串传递给XSSFRichTextString,但它显示输出文件中的HTML字符串。

我正在使用Apache POI 3.16

Screenshot to explain the requirement

1 个答案:

答案 0 :(得分:1)

您在想,RichTextString应该能够解释HTML吗?它不是。它只能从startIndexendIndex apply FontFont可以使用TypeOffset SS_SUPER进行标记。

示例:

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();
  } 
 }
}
相关问题