如何使用最新的apache poi设置粗体字体?

2024-02-12

我用的是最新的apache poi

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

但我无法设置粗体字体,下面的代码不起作用

font.setBold(true);

因为默认为 true

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

并且不存在setBoldWeight方法要么

那么如何在最新的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

大胆的效果应该是这样的


Mac 数字无法解释<b val="true"/>正确。但这违反了规范。看xmlschema-2 布尔值 https://www.w3.org/TR/xmlschema-2/#boolean:“定义为·boolean·的数据类型实例可以具有以下合法文字{true, false, 1, 0}。”。

但它会解释<b />正确。这对于标记 a 也有效Font要大胆。这也意味着“如果省略,则默认值为 true”。如果b标签存在但没有值,也没有true nor false,那么它默认为true。设置不粗体b必须删除或设置标签<b val="false"/> or <b val="0"/>. There apache poi做到最好,最兼容。它删除了b tag.

同样是为了i滑石粉和s三振。

提示apache poi开发团队:考虑设置<b />, <i /> and <s />没有要设置的值true。这将是最兼容的。

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);
  }

 }

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用最新的apache poi设置粗体字体? 的相关文章

随机推荐