如何将单元格合并到poi中的最后一行
我正在创build一个工作簿使用Apache poi,我想合并一个特定的单元格到输出的结尾。我正在使用mergeRegion函数和单元格正在合并,但该单元格不合并到行的末尾,它总是结束一行之前,
我在这里附加屏幕合并单元格
我想单元格被合并,我在这里张贴我的代码
for(MarshActiveUser marshActiveUser : listOfMarshUser){ /***/ sheet.addMergedRegion(new CellRangeAddress( j, //first row (0-based) j, //last row (0-based) 18, //first column (0-based) 20 //last column (0-based) )); /***/ int columnNo = 0; row = sheet.createRow(j+1); cell = row.createCell(columnNo); cell.setCellValue(new HSSFRichTextString(String.valueOf(row.getRowNum()))); lockedCellStyle.setFont(hSSFFont); sheet.autoSizeColumn(0); cell.setCellStyle(lockedCellStyle); columnNo = 1; cell = row.createCell(columnNo); if(null != marshActiveUser.getFistName()){ cell.setCellValue(new HSSFRichTextString(marshActiveUser.getFistName())); lockedCellStyle.setFont(hSSFFont); sheet.autoSizeColumn(1); cell.setCellStyle(lockedCellStyle); }else{ cell.setCellValue(new HSSFRichTextString(" ")); cell.setCellStyle(lockedCellStyle); }
我试图从rowCount + 1开始,但是这是不允许的代码,请帮助我。提前感谢。
rowCount增量有一个问题。 预增加行计数是跳过您的最后一行合并。 将其更改为增量rowcount++
,并按预期工作。
import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.CellRangeAddress; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; public class SimpleExcelWriterExample { public static void main(String[] args) throws IOException { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Java Books"); Object[][] bookData = { {"Head First Java", "Kathy Serria", 79}, {"Effective Java", "Joshua Bloch", 36}, {"Clean Code", "Robert martin", 42}, {"Thinking in Java", "Bruce Eckel", 35}, }; int rowCount = 1; for (Object[] aBook : bookData) { /***/ sheet.addMergedRegion(new CellRangeAddress( rowCount, //first row (0-based) rowCount, //last row (0-based) 3, //first column (0-based) 5 //last column (0-based) )); /***/ Row row = sheet.createRow(rowCount++); int columnCount = 0; for (Object field : aBook) { Cell cell = row.createCell(++columnCount); if (field instanceof String) { cell.setCellValue((String) field); } else if (field instanceof Integer) { cell.setCellValue((Integer) field); } } } try{ FileOutputStream outputStream = new FileOutputStream("D://JavaBooks.xls"); workbook.write(outputStream); }catch(Exception e){} }}
输出: