Почему XSSFRichTextString.applyFont () не работает так, как написано в java doc? - PullRequest
0 голосов
/ 08 октября 2019

Я пытаюсь применить жирный шрифт к частям строки и поместить его в ячейку.

XSSFFont font = workbook.createFont();
font.setBold(true);
XSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
XSSFCell c = nextRow.createCell(4);
c.setCellStyle(style);
XSSFRichTextString string = new XSSFRichTextString(report.getSurroundText());
string.applyFont( startIndex, getEndOfWord(startIndex, report.getFoundWord()), font); 
c.setCellValue(string);

Этот код, как часть моего кода, который создает файл .xlsx и производитфайл не поврежден, но текст, который должен быть выделен жирным шрифтом, неверен. Вместо этого он выделяется от начала текста до индекса, который я установил как конечный индекс в методе applyFont(). По какой-то причине startIndex игнорируется.

Во время отладки оба значения startIndex и возвращаемое значение getEndOfWord() являются правильными.

РЕДАКТИРОВАТЬ:

try(FileOutputStream fileOut = new FileOutputStream(new File(directory.getAbsoluteFile() + File.separator + 
            FilenameUtils.getBaseName(csvFile.getAbsolutePath()) + ".xlsx"));) {
        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
            XSSFSheet sheet = workbook.createSheet("Highlights");
            XSSFRow headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue(firstLine);

            XSSFRow titleRow = sheet.createRow(1);
            titleRow.createCell(0).setCellValue(SCANID);
            titleRow.createCell(1).setCellValue(DOCID);
            titleRow.createCell(2).setCellValue(FOUNDWORD);
            titleRow.createCell(3).setCellValue(OFFSET);
            titleRow.createCell(4).setCellValue(SURROUNDTEXT);

            XSSFFont font = workbook.createFont();
            font.setBold(true);
            XSSFFont deFont = workbook.createFont();
            font.setBold(false);

            int row = 2;
            for (MuiDetailReport report : lst) {
                XSSFRow nextRow = sheet.createRow(row);
                nextRow.createCell(0).setCellValue(report.getScanId());
                nextRow.createCell(1).setCellValue(report.getDocId());
                nextRow.createCell(2).setCellValue(report.getFoundWord());
                if (report.getOffset() != 0) nextRow.createCell(3).setCellValue(report.getOffset());
                else nextRow.createCell(3).setCellValue("");
                if (!report.getFoundWord().isBlank() && !report.getSurroundText().isBlank()) {
                    int startIndex = getStartOfWord(report.getFoundWord(), report.getSurroundText());
                    if (startIndex == -1) nextRow.createCell(4).setCellValue("");
                    else {
                        XSSFCell c = nextRow.createCell(4);
                        XSSFRichTextString string = new XSSFRichTextString(report.getSurroundText());
                        string.applyFont(startIndex, getEndOfWord(startIndex, report.getFoundWord()), font);
                        c.setCellValue(string);
                    }
                } else nextRow.createCell(4).setCellValue("");
                row++;
            }
            workbook.write(fileOut);
        }
        fileOut.flush();
    }

Это мой метод для создания моего .xlsx файла. Параметр метода: String firstLine, List<MuiDetailReport> lst, File csvFile. Переменная со всеми заглавными символами static final String

Мой результат " Hellomyname isThad" вместо "Hellomy name isThad"

Ответы [ 2 ]

1 голос
/ 08 октября 2019

Давайте получим действительно Минимальный, воспроизводимый пример .

В результате следует следующий текст:

Hellomy name isThad

в ячейке A1.

import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

class CreateExcelBoldWord {

 public static void main(String[] args) throws Exception {

  Workbook workbook = new XSSFWorkbook(); 
  //Workbook workbook = new HSSFWorkbook();

  String fileName = (workbook instanceof XSSFWorkbook)?"Excel.xlsx":"Excel.xls";

  CreationHelper creationHelper = workbook.getCreationHelper();

  Font font = workbook.createFont(); // default font
  Font fontBold = workbook.createFont();
  fontBold.setBold(true);

  String text = "HellomynameisThad";
  String word = "name";

  RichTextString richTextString = creationHelper.createRichTextString(text);
  int startIndex = text.indexOf(word);
  int endIndex = startIndex + word.length();
  richTextString.applyFont(startIndex, endIndex, fontBold);

  Sheet sheet = workbook.createSheet();
  sheet.createRow(0).createCell(0).setCellValue(richTextString);

  FileOutputStream out = new FileOutputStream(fileName);
  workbook.write(out);
  out.close();
  workbook.close();
 }
}

Нет?

0 голосов
/ 08 октября 2019

Я получил его с помощью , не применяя CellStyle к ячейке и просто устанавливая XSSFRichTextString в качестве значения ячейки.

См. Этот пример, который предполагает уже созданныйXSSFWorkbook и XSSFSheet:

XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(0);
XSSFFont boldFont = new XSSFFont();
boldFont.setBold(true);
XSSFRichTextString rts = new XSSFRichTextString("BVB BVB BVB");
rts.applyFont(4, 7, boldFont);
cell.setCellValue(rts);

Я пропустил часть, которая записывает книгу в файловую систему, я думаю, ваша уже работает.

Результатом этого являетсяРабочая тетрадь с надписью "BVB BVB BVB" в первой / верхней левой ячейке.

Это часть моего pom.xml (проект maven), где установлены зависимости apache poi, возможно, у вас естьстарая версия:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.0</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.0</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.1.0</version>
</dependency>
...