Java 使用 Apache POI 将整行加粗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25437431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make the entire row bold using Apache POI
提问by rickygrimes
I am using Apache POI's HSSFWorkbook to write data to Excel spreadsheets.
我正在使用 Apache POI 的 HSSFWorkbook 将数据写入 Excel 电子表格。
I want to make an entire row bold. Can someone please suggest how to do it?
我想让整行加粗。有人可以建议怎么做吗?
采纳答案by Levenal
Would something like this work with what you have:
像这样的东西会与你所拥有的一起工作吗:
public static void makeRowBold(Workbook wb, Row row){
CellStyle style = wb.createCellStyle();//Create style
Font font = wb.createFont();//Create font
font.setBold(true);//Make font bold
style.setFont(font);//set it to bold
for(int i = 0; i < row.getLastCellNum(); i++){//For each cell in the row
row.getCell(i).setCellStyle(style);//Set the style
}
}
It basically goes over each cell in the row passed in, setting the style to a bold one. Should result in the whole row being set to the desired style.
它基本上遍历传入的行中的每个单元格,将样式设置为粗体。应将整行设置为所需的样式。
Good Luck!
祝你好运!
EDIT
编辑
A more complete example:
一个更完整的例子:
public static void main(String[] args) {
Path myFile = Paths.get(System.getProperty("user.home"), "Desktop", "tester.xlsx");
try {
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(myFile.toFile()));
XSSFSheet sheet = wb.getSheetAt(0);
makeRowBold(wb, sheet.getRow(0));
wb.write(new FileOutputStream(myFile.toFile()));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void makeRowBold(Workbook wb, Row row){
CellStyle style = wb.createCellStyle();//Create style
Font font = wb.createFont();//Create font
font.setBold(true);//Make font bold
style.setFont(font);//set it to bold
for(int i = 0; i < row.getLastCellNum(); i++){//For each cell in the row
row.getCell(i).setCellStyle(style);//Set the sty;e
}
}
This was tested on an xlsx file with data in row 1, the resulting file had bold data afterwards.
这是在第 1 行数据的 xlsx 文件上进行测试的,结果文件之后有粗体数据。
回答by BullyWiiPlaza
Using the non-deprecated API:
使用未弃用的 API:
public static void makeBold(Workbook workbook, Row row)
{
CellStyle cellStyle = cell.getCellStyle();
cellStyle.setFont(font);
for (int rowIndex = 0; rowIndex < row.getLastCellNum(); rowIndex++)
{
Cell cell = row.getCell(rowIndex);
XSSFFont font = (XSSFFont) workbook.createFont();
font.setBold(true);
cell.setCellStyle(cellStyle);
}
}