简体   繁体   English

XSSFWorkbook 使用 apache poi 使部分单元格内容加粗

[英]XSSFWorkbook make part of cell content to bold using apache poi

My project need is to make part of a string bold leaving any OR and AND like the below example.我的项目需要将字符串的一部分设为粗体,保留任何 OR 和 AND,如下例所示。

TOWING PACK 11 OR TOWING PACK 13 AND TOWING PACK 14 OR TOWING PACK 15拖车包 11拖车包 13拖车包 14拖车包 15

I tried to follow the reverse approach.我试图遵循相反的方法。

  1. I tried to make the entire cell BOLD // This works我试着把整个单元格设为粗体 // 这行得通
  2. Then using RichTextString make "OR" and "AND" to normal Italics.然后使用 RichTextString 将“OR”和“AND”变为普通斜体。 //The issue - After the first "OR" all the rest of the string is formatted to normal format. //问题 - 在第一个“或”之后,字符串的所有 rest 都被格式化为正常格式。

Output I am getting: Output 我得到:

TOWING PACK 11 OR TOWING PACK 13 AND TOWING PACK 14 OR TOWING PACK 15拖车包 11拖车包 13 和拖车包 14 或拖车包 15

I am using poi 5.2.3 and below is the code sample.我正在使用 poi 5.2.3,下面是代码示例。 Can anyone point out what is wrong here.谁能指出这里出了什么问题。

   CreationHelper creationHelper = workbook.getCreationHelper();
    XSSFFont fontBold = workbook.createFont();
    fontBold.setBold(true);
    XSSFFont fontItalic = workbook.createFont();
    fontItalic.setItalic(true);
    fontItalic.setBold(false);

    XSSFCellStyle boldstyle = workbook.createCellStyle();
    boldstyle.setFont(fontBold);
    int startrow = 2;
    Iterator<Row> boldrowIterator = spreadsheet.iterator();
    while (boldrowIterator.hasNext()) {
        Row boldrow = boldrowIterator.next();
        if (boldrow.getRowNum()==startrow) {
        out.println(boldrow.getCell(9));
        Cell boldcell = boldrow.getCell(9);
        boldcell.setCellStyle(boldstyle);
    startrow = startrow+1;

            String Featuredescription = boldrow.getCell(9).getStringCellValue();
            if (Featuredescription.contains("OR")) {
                RichTextString richTextString = creationHelper.createRichTextString(Featuredescription);
                String word = " OR ";
                int startIndex = Featuredescription.indexOf(word);
                int endIndex = startIndex + word.length();
                out.println("Featuredescription: " + Featuredescription + startIndex + endIndex);
                richTextString.applyFont(startIndex, endIndex, fontItalic);
                boldcell.setCellValue(richTextString);
            }
        } }

I would recommend using a simple regular expression to find all the occurrences of AND and OR (note the spaces included in these strings).我建议使用简单的正则表达式来查找所有出现的ANDOR (注意这些字符串中包含的空格)。 Doing this lets you easily determine the location of each occurrence within the overall string (the indexes of where each word starts and ends).这样做可以让您轻松确定整个字符串中每次出现的位置(每个单词开始和结束位置的索引)。 You can use this to set everything to bold (like you are already doing) and then set each OR and AND to normal.您可以使用它来将所有内容设置为粗体(就像您已经在做的那样),然后将每个ORAND设置为正常。

My code assumes your test text is in cell A1 - and that is the only cell I test.我的代码假定您的测试文本位于单元格 A1 中 - 这是我测试的唯一单元格。 You can add back your looping logic to handle more cells.您可以添加回循环逻辑以处理更多单元格。

You will also need:您还需要:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

I have added comments to the code to explain specific lines:我在代码中添加了注释以解释特定行:

FileInputStream file = new FileInputStream(new File("C:/temp/poi/rich_formatting_in.xlsx"));
Workbook wb = new XSSFWorkbook(file);
Sheet sheet = wb.getSheet("Sheet1");
CreationHelper creationHelper = wb.getCreationHelper();

Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
String content = cell.getStringCellValue();

Font bold = wb.createFont();
bold.setBold(true);

Font normal = wb.createFont();
normal.setBold(false);
//normal.setItalic(true); // uncomment, if you need italics, as well.

RichTextString richStr = creationHelper.createRichTextString(content);
richStr.applyFont(bold); // set everything to bold

String regex = "( AND | OR )"; // note the spaces in the strings

Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(content);

while (matcher.find()) {
    // process each found group (one group for each AND and OR):
    for (int i = 1; i <= matcher.groupCount(); i++) {
        // matcher.start(i) finds where the start of the match is
        // matcher.end(i) finds the position of the end of the match
        // we can use these start and end positions to set that text to normal:
        richStr.applyFont(matcher.start(i), matcher.end(i), normal);
    }
}

// write the final string to the spreadsheet:
cell.setCellValue(richStr);

// write the spreadsheet to a file so we can see the results:
try (FileOutputStream out = new FileOutputStream(new File("C:/temp/poi/rich_formatting_out.xlsx"))) {
    wb.write(out);
}

The results are:结果是:

在此处输入图像描述


The regex ( AND | OR ) is very basic - it assumes every occurrence of the words AND and OR surrounded by spaces are what need to be adjusted.正则表达式( AND | OR )是非常基本的——它假定每一次出现的单词ANDOR都需要被空格包围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM