如何使用Java POI将下划线设置为空格

问题描述 投票:0回答:1

我尝试使用

XWPFRun.setUnderline
设置下划线,但当我尝试使用空格字符串时它不起作用。 代码如下:

public static void setFilingParagraph(XWPFDocument doc, String beforeStr,String afterStr) {
    XWPFParagraph p = doc.createParagraph();
    p.setAlignment(ParagraphAlignment.LEFT);
    p.setSpacingBeforeLines(50);
    p.setSpacingAfterLines(50);
    XWPFRun r = p.createRun();
    r.setBold(false);
    r.setText(beforeStr);
    r.setColor("000000");
    r.setFontSize(14);
    if (afterStr != null) {
        XWPFRun run = p.createRun();
        run.setText(afterStr);
        run.setColor("000000");
        run.setUnderline(UnderlinePatterns.SINGLE);
        run.setFontSize(14);
    }
}

afterStr
为(例如)
"             "
时,
run.setUnderline(UnderlinePatterns.SINGLE);
不起作用。 如何处理这个问题呢?谢谢。

java apache-poi
1个回答
0
投票

这就是 Microsoft Word 处理空格下划线的方式。它强调单词之间的简单空格。但它不会强调后面没有任何字符的简单空格。尽管如此,它还是强调了不间断的空格。

示例:

import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;

public class CreateWordUnderlined {
    
 public static void setFilingParagraph(XWPFDocument doc, String beforeStr, String afterStr) {
  XWPFParagraph p = doc.createParagraph();
  p.setAlignment(ParagraphAlignment.LEFT);
  p.setSpacingBeforeLines(50);
  p.setSpacingAfterLines(50);
  XWPFRun r = p.createRun();
  r.setBold(false);
  r.setText(beforeStr);
  r.setColor("000000");
  r.setFontSize(14);
  if (afterStr != null) {
   XWPFRun run = p.createRun();
   run.setText(afterStr);
   run.setColor("000000");
   run.setUnderline(UnderlinePatterns.SINGLE);
   run.setFontSize(14);
  }
 }

 public static void main(String[] args) throws Exception {
  try ( FileOutputStream out = new FileOutputStream("./CreateWordUnderlined.docx");  
        XWPFDocument doc = new XWPFDocument(); ) {
            
   String beforeStr = "A sample text ";
   String afterStr = "             "; // only simple spaces will not be underlined
   setFilingParagraph(doc, beforeStr, afterStr);
   afterStr = "             ."; // spaces folowed by a character will be underlined
   setFilingParagraph(doc, beforeStr, afterStr);
   afterStr = "            \u00A0"; // spaces folowed by a non breaking space will be underlined
   setFilingParagraph(doc, beforeStr, afterStr);
   afterStr = "\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0"; // non breaking spaces will be underlined
   setFilingParagraph(doc, beforeStr, afterStr);

   doc.write(out);
  }
 }
}

结果:

© www.soinside.com 2019 - 2024. All rights reserved.