我想使用 Apache poi 将数据导出到Excel .
现在我遇到的问题是我无法合并行并将它们对齐在中心 .
出口数据代码是:
List<LinkedHashMap<String,Object>> lstReportHeader = null;
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
//Set Header Font
HSSFFont headerFont = wb.createFont();
headerFont.setBoldweight(headerFont.BOLDWEIGHT_BOLD);
headerFont.setFontHeightInPoints((short) 12);
//Set Header Style
CellStyle headerStyle = wb.createCellStyle();
headerStyle.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
headerStyle.setAlignment(headerStyle.ALIGN_CENTER);
headerStyle.setFont(headerFont);
headerStyle.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
int rowCount= 0;
Row header;
header = sheet.createRow(0);//its for header
Cell cell ;//= header.createCell(0);
for(int j = 0;j < 4; j++) {
cell = header.createCell(j);
if(j == 0) {
cell.setCellValue("ItemWise List");
}
cell.setCellStyle(headerStyle);
}
sheet.addMergedRegion(new CellRangeAddress(rowCount, rowCount, 0, lstReportFormHeader.size()-1));
header = sheet.createRow(0);
cell = header.createCell(0);
cell.setCellValue("Sr. No");
cell = header.createCell(1);
cell.setCellValue("Item Name");
cell = header.createCell(2);
cell.setCellValue("Qty");
cell = header.createCell(3);
cell.setCellValue("Rate");
现在我想 ItemWise List 合并并使其对齐中心 .
8 回答
我的解决方案是按位置合并单元格,然后创建一个单元格(引用合并单元格的第一个块)来分配值,然后通过CellUtil设置对齐方式 .
合并:::
对齐也请查看Apache poi的以下官方链接:::
http://poi.apache.org/spreadsheet/quick-guide.html#Alignment
经过研究,我发现在合并7个单元格后,合并的单元格id将为0,因此我使用以下样式将以下样式应用于单元格ID 0 .
根据我的理解,您有合并的开始和结束单元格,并且您希望合并单元格范围并对齐单元格内容 . 如果我是对的,您可以使用以下方法:
那么对我有用的是将所有合并的单元格'Cellstyle设置为CENTER ALIGN . 是否在将cellstyle值设置为center之前或之后放置XSSFSheet.addMergedRegion()方法无关紧要 .
如上所述,可以使用合并单元来实现
但是为了垂直对齐细胞,最近我面临类似的问题,我尝试了上面的答案,但使用
对齐日期格式化单元格为水平左对齐 . 所以我使用以下方法仅设置Cell内容的Vertical Alignment .
我希望这有帮助!!
Happy Coding
这对我有用,我认为它更清洁:
使用
设置垂直对齐而不是