Reputation: 47
I am trying to create rowspan and colspan in apache poi.Can you tell me how i can accomplish something like this.I have tried using addMergedRegion method but that seem to be doing only colspan
<table border="1">
<tr>
<td rowspan="2">Month</td>
<td colspan="2">Savings</td>
</tr>
<tr>
<td>January</td>
<td>feb</td>
</tr>
</table>
Upvotes: 2
Views: 7854
Reputation: 61860
From your hint to addMergedRegion
I suspect you are talking about the Excel
parts of apache poi
.
There it works for me using Java
and apache poi
version 3.17
as in the following example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellUtil;
public class CreateExcelMergedRegions {
public static void main(String[] args) throws Exception {
/*
goal:
+---------+---------+----------+
| A | B | C |
+---+------------------------------+
| 1 | | Savings |
+---+ Month |--------------------+
| 2 | | January | February |
+---+---------+---------+----------+
*/
Workbook workbook = new XSSFWorkbook();
//Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet();
CellRangeAddress mergedRegion = new CellRangeAddress(0,0,1,2); // row 1 col B and C
sheet.addMergedRegion(mergedRegion);
mergedRegion = new CellRangeAddress(0,1,0,0); // row 1 and 2 col A
sheet.addMergedRegion(mergedRegion);
Row row = sheet.createRow(0); // row 1
Cell cell = row.createCell(0); // cell A1
cell.setCellValue("Month");
// set vertical alignment center
CellUtil.setCellStyleProperty(cell, CellUtil.VERTICAL_ALIGNMENT, VerticalAlignment.CENTER);
cell = row.createCell(1); // cell B1
cell.setCellValue("Savings");
// set horizontal alignment center
CellUtil.setCellStyleProperty(cell, CellUtil.ALIGNMENT, HorizontalAlignment.CENTER);
row = sheet.createRow(1); // row 2
cell = row.createCell(1); // cell B2
cell.setCellValue("January");
cell = row.createCell(2); // cell C2
cell.setCellValue("February");
if (workbook instanceof XSSFWorkbook) {
FileOutputStream out = new FileOutputStream("CreateExcelMergedRegions.xlsx");
workbook.write(out);
out.close();
} else if (workbook instanceof HSSFWorkbook) {
FileOutputStream out = new FileOutputStream("CreateExcelMergedRegions.xls");
workbook.write(out);
out.close();
}
workbook.close();
}
}
I suspect you had missed the setting of alignment?
Upvotes: 8