I used the latest apache poi
org.apache.poi
poi-ooxml
3.17
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

解决方案
The Mac Numbers does not interpret 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 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 or . 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 , and 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); // does not work using Mac Numbers
font.getCTFont().addNewB(); // maybe will work?
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
try (FileOutputStream fos = new FileOutputStream("bold_test.xlsx")) {
wb.write(fos);
}
}
}