如何使用Java Apache POI在Excel中dynamic构build边界
所以在我的java类中,我有以下代码。
int rowNum = 11; Row myRow = null; Cell myCell = null; for (Object obj : details) { Object[] objArr = (Object[]) obj; String header = ""; String value = ""; if (objArr[0] != null) { header = objArr[0].toString(); myRow = sheet.createRow((short) rowNum); myCell = myRow.createCell(1); myCell.setCellValue(header); } if (objArr[1] != null) { value = objArr[1].toString(); myCell = myRow.createCell(6); myCell.setCellValue(value); myCell.setCellStyle(style); } rowNum++; }
和边界
for (int i = 0; i < objArr.length; i++) { Cell columnHeaderCell = myRow.createCell(i); columnHeaderCell.setCellValue((Double) objArr[i]); columnHeaderCell.setCellStyle(columnHeaderStyle); }
问题是边界重叠在数据的顶部,并为所有单元格创build边界。 如何在java中dynamic创build一个2 X 10 *(x)表?
使用Apache POI可以设置边界如下。
find下面的示例,这可能会帮助你。
/* Create Workbook and Worksheet */ HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Colored Cell Border"); HSSFCellStyle style = workbook.createCellStyle(); /* Set Borders thickness */ style.setBorderLeft(HSSFCellStyle.BORDER_THICK); style.setBorderRight(HSSFCellStyle.BORDER_THICK); style.setBorderTop(HSSFCellStyle.BORDER_THICK); style.setBorderBottom(HSSFCellStyle.BORDER_THICK); /* Get Color Index */ style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); /* Add border color to a cell */ Row row = sheet.createRow(0); Cell cell = row.createCell(0); cell.setCellValue("Different border colors for a Cell"); cell.setCellStyle(my_style);
我做了以下几件事情。 获取数据的对象。 所以对于空单元格,validation对象!= null 。
我的代码:
int rowNum = 1; Row myRow = null; Row emptyRow = null; Cell myCell = null; Cell emptyCell =null; for (Object obj : details) { Object[] objArr = (Object[]) obj; String header = ""; String value = ""; if(objArr[0]==null){ emptyRow = sheet.createRow((short) rowNum); emptyCell = emptyRow.createCell(0); emptyCell.setCellValue(""); emptyCell.setCellStyle(style); } if(objArr[1]==null){ emptyCell = emptyRow.createCell(1); emptyCell.setCellValue(value); emptyCell.setCellStyle(style); }
用边界dynamic构build行:
build筑标题栏:
if (objArr[0] != null) { header = objArr[0].toString(); myRow = sheet.createRow((short) rowNum); myCell = myRow.createCell(0); for (int i = 0; i < 2; i++) { Cell columnHeaderCell = myRow.createCell(i); columnHeaderCell.setCellValue(""); columnHeaderCell.setCellStyle(style); } }
build筑价值栏:
if (objArr[1] != null) { value = objArr[1].toString(); myCell = myRow.createCell(1); myCell.setCellValue(value); myCell.setCellStyle(style); } rowNum++; }
上面的括号是closuresfor each
循环。
为边界
HSSFCellStyle style=wb.createCellStyle(); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN);