我想将第2列和excel工作表中最后一列的所有单元格的边界设置为粗线,其他的都细线。但是结果是所有列的边框都很粗。
这是我的代码
for(int i = 0; i < sheet.getLastRowNum(); i++){
HSSFRow row = sheet.getRow(i);
for (int j = 0; j < row.getLastCellNum(); j++) {
HSSFCell cell = row.getCell(j);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
if(j == 1 || j == row.getLastCellNum()-1){
style.setBorderRight(HSSFCellStyle.BORDER_THICK);
}
style.setTopBorderColor(HSSFColor.BLACK.index);
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setLeftBorderColor(HSSFColor.BLACK.index);
style.setRightBorderColor(HSSFColor.BLACK.index);
System.out.println("Row:"+i+", Column:"+j+", BorderRightStyleIndex:"+style.getBorderRight());
cell.setCellStyle(style);
}
}
这是控制台中的信息
Row:355, Column:0, BorderRightStyleIndex:1
Row:355, Column:1, BorderRightStyleIndex:5
Row:355, Column:2, BorderRightStyleIndex:1
Row:355, Column:3, BorderRightStyleIndex:1
Row:355, Column:4, BorderRightStyleIndex:1
Row:355, Column:5, BorderRightStyleIndex:1
Row:355, Column:6, BorderRightStyleIndex:1
Row:355, Column:7, BorderRightStyleIndex:1
Row:355, Column:8, BorderRightStyleIndex:1
Row:355, Column:9, BorderRightStyleIndex:1
Row:355, Column:10, BorderRightStyleIndex:5
Row:356, Column:0, BorderRightStyleIndex:1
Row:356, Column:1, BorderRightStyleIndex:5
Row:356, Column:2, BorderRightStyleIndex:1
Row:356, Column:3, BorderRightStyleIndex:1
Row:356, Column:4, BorderRightStyleIndex:1
Row:356, Column:5, BorderRightStyleIndex:1
Row:356, Column:6, BorderRightStyleIndex:1
Row:356, Column:7, BorderRightStyleIndex:1
Row:356, Column:8, BorderRightStyleIndex:1
Row:356, Column:9, BorderRightStyleIndex:1
Row:356, Column:10, BorderRightStyleIndex:5
我的代码哪一部分出错了?为什么所有列的边框都很粗?
答案 0 :(得分:1)
Excel
的单元格样式存储在工作簿级别。这就是apache poi
的{{1}}也处于CellStyles
级别的原因。因此,在您的代码中只有一个Workbook
CellStyle
。根据您的代码,所有单元格都会应用相同的style
。因此,该style
的最后设置是所使用的设置。那是那些右边框粗的。
您至少需要两个style
,一个不带边框,另一个带右边框。然后根据需要将两种单元格样式之一应用于您的CellStyles
。
另一种方法是使用DrawingBorders中所示的Cell
。我认为这是最佳做法,因此我将向您展示如何做到这一点。以下代码首先在表格区域中的所有单元格周围绘制细边框线。然后在表格区域的第二列和最后一列中另外绘制一条粗的右边界线。
PropertyTemplate