如何使用最新的Apache POI设置粗体字体? [英] How to set bold font using the latest apache poi?
问题描述
我使用了最新的apache poi
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);
因为默认为true
set a boolean value for the boldness to use. If omitted, the default value is true.
并且也不存在setBoldWeight
方法
那么如何在最新的Apache poi中设置粗体?
So how can I set bold weight in the latest apache poi?
代码
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);
}
效果
大胆的效果应该是这样的
and the bold effect should like this
推荐答案
Mac Numbers无法正确解释<b val="true"/>
.但这违反了规范.请参见 xmlschema-2布尔:已定义数据类型的实例as·boolean·可以具有以下合法文字{true,false,1,0}..
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}. ".
但是它将正确解释<b />
.将Font
标记为粗体也是有效的.这也意味着如果省略,则默认值为true".如果b
标记在那里但没有值,既不是true
也不是false
,则默认为true
.要设置为非粗体,必须删除b
标记,或者必须将其设置为<b val="false"/>
或<b val="0"/>
. apache poi
表现最好,最兼容.它会删除b
标签.
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.
对于i
talic和s
trikeout来说是相同的.
Same is for i
talic and s
trikeout.
apache poi
开发人员团队的提示:考虑设置<b />
,<i />
和<s />
,但不设置true
的值.这将是最兼容的.
Hint for apache poi
developer team: Consider setting <b />
, <i />
and <s />
without values to set true
. This will be the most compatible.
尝试:
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);
}
}
}
这篇关于如何使用最新的Apache POI设置粗体字体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!