java – 使用Apache POI使整行变粗

前端之家收集整理的这篇文章主要介绍了java – 使用Apache POI使整行变粗前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Apache POI的HSSFWorkbook将数据写入Excel电子表格.

我想整整一行加粗.有人可以建议怎么做吗?

解决方法

像这样的东西可以用你所拥有的东西:
  1. public static void makeRowBold(Workbook wb,Row row){
  2. CellStyle style = wb.createCellStyle();//Create style
  3. Font font = wb.createFont();//Create font
  4. font.setBold(true);//Make font bold
  5. style.setFont(font);//set it to bold
  6.  
  7. for(int i = 0; i < row.getLastCellNum(); i++){//For each cell in the row
  8. row.getCell(i).setCellStyle(style);//Set the style
  9. }
  10. }

它基本上遍历传入的行中的每个单元格,将样式设置为粗体.应该导致整行被设置为所需的样式.

祝好运!

编辑

一个更完整的例子:

  1. public static void main(String[] args) {
  2. Path myFile = Paths.get(System.getProperty("user.home"),"Desktop","tester.xlsx");
  3.  
  4. try {
  5. XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(myFile.toFile()));
  6. XSSFSheet sheet = wb.getSheetAt(0);
  7. makeRowBold(wb,sheet.getRow(0));
  8.  
  9. wb.write(new FileOutputStream(myFile.toFile()));
  10. } catch (IOException e) {
  11. e.printStackTrace();
  12. }
  13. }
  14.  
  15.  
  16. public static void makeRowBold(Workbook wb,Row row){
  17. CellStyle style = wb.createCellStyle();//Create style
  18. Font font = wb.createFont();//Create font
  19. font.setBold(true);//Make font bold
  20. style.setFont(font);//set it to bold
  21.  
  22. for(int i = 0; i < row.getLastCellNum(); i++){//For each cell in the row
  23. row.getCell(i).setCellStyle(style);//Set the sty;e
  24. }
  25. }

这是在xlsx文件上测试的,数据在第1行,结果文件后面有粗体数据.

猜你在找的Java相关文章