How to set bold font using the latest apache poi?

大兔子大兔子 提交于 2020-03-05 05:12:30

问题


I used the latest apache poi

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

but I cannot set bold font, below code does not work

font.setBold(true);

because the default it true

set a boolean value for the boldness to use. If omitted, the default value is true.

and does not exist setBoldWeight method either

So how can I set bold weight in the latest apache poi?


code

XSSFWorkbook wb = new XSSFWorkbook()
XSSFSheet sheet = wb.createSheet();
XSSFCell cell = sheet.createRow(0).createCell(0);
cell.setCellValue("hello world");

XSSFCellStyle cellStyle = wb.createCellStyle();
XSSFFont font = wb.createFont();
font.setBold(true);
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);

try (FileOutputStream fos = new FileOutputStream("bold_test.xls")) {
    wb.write(fos);
}

effect

and the bold effect should like this


回答1:


The Mac Numbers does not interpret <b val="true"/> correctly. But this violates the specification. See xmlschema-2 boolean: "An instance of a datatype that is defined as ·boolean· can have the following legal literals {true, false, 1, 0}. ".

But it will interpret <b /> correctly. This also is valid to flag a Font to be bold. And this also is meant with "If omitted, the default value is true.". If the b tag is there but does not have a value, neither true nor false, then it defaults to true. To set not bold either the b tag must be removed or must be set <b val="false"/> or <b val="0"/>. There apache poi does the best, most compatible. It removes the b tag.

Same is for italic and strikeout.

Hint for apache poideveloper team: Consider setting <b />, <i /> and <s /> without values to set true. This will be the most compatible.

Try:

import java.io.FileOutputStream;

import org.apache.poi.xssf.usermodel.*;

public class CreateExcelFontBold {

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

  XSSFWorkbook wb = new XSSFWorkbook();
  XSSFSheet sheet = wb.createSheet();
  XSSFCell cell = sheet.createRow(0).createCell(0);
  cell.setCellValue("hello world");

  XSSFCellStyle cellStyle = wb.createCellStyle();
  XSSFFont font = wb.createFont();
  //font.setBold(true); // <b val="true"/> does not work using Mac Numbers
  font.getCTFont().addNewB(); // maybe <b /> will work?
  cellStyle.setFont(font);
  cell.setCellStyle(cellStyle);

  try (FileOutputStream fos = new FileOutputStream("bold_test.xlsx")) {
   wb.write(fos);
  }

 }

}



回答2:


Actually it's the Mac Numbers bug



来源:https://stackoverflow.com/questions/49253199/how-to-set-bold-font-using-the-latest-apache-poi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!