java - 使用 apache poi 合并和对齐中心单元格

标签 java excel apache-poi

我想使用 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合并并使其居中对齐。

最佳答案

我的解决方案是按单元格的位置合并单元格,然后创建一个单元格(引用合并单元格的第一个 block )来分配一个值,然后通过 CellUtil 设置对齐方式

// Merges the cells
CellRangeAddress cellRangeAddress = new CellRangeAddress(start, start, j, j + 1);
sheet.addMergedRegion(cellRangeAddress);

// Creates the cell
Cell cell = CellUtil.createCell(row, j, entry.getKey());

// Sets the allignment to the created cell
CellUtil.setAlignment(cell, workbook, CellStyle.ALIGN_CENTER);

关于java - 使用 apache poi 合并和对齐中心单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20093813/

相关文章:

string - VBA 如果单元格中的前 6 个字符不等于 01/01/then

Javascript表导出到excel utf8

java - Apache poi迁移到jdk 11问题

java - 如何使用 Apache POI 将图片大小调整为段落大小?

javascript - NodeJs 相当于 Java getBytes()

java - 我想将图像大小减小到 64 KiB 以保存在 mySql 数据库中

Excel VBA 组合框清除

java - 如何在使用 Apache poi 阅读之前保存 Excel Activity 工作表?有没有类似 WorkSheet.save(); 的东西或 WorkSheet.comit()?

Java - AttachNotSupportedException : Unable to open socket file: HotSpot VM not loaded

java - 生成漂亮的 JAXB 类