Independentsoft
Any library, any programming language
Home
Purchase
Support
Company
Contact
JWord
>
Tutorial
> Horizontally merged cells
The following example shows you how to create horizontally merged table cells.
import com.independentsoft.office.word.Paragraph; import com.independentsoft.office.word.Run; import com.independentsoft.office.word.StandardBorderStyle; import com.independentsoft.office.word.WordDocument; import com.independentsoft.office.word.tables.Cell; import com.independentsoft.office.word.tables.CellProperties; import com.independentsoft.office.word.tables.HorizontallyMergedCell; import com.independentsoft.office.word.tables.MergeCellType; import com.independentsoft.office.word.tables.Row; import com.independentsoft.office.word.tables.Table; import com.independentsoft.office.word.tables.TableWidthUnit; import com.independentsoft.office.word.tables.Width; public class Example { public static void main(String[] args) { try { WordDocument doc = new WordDocument(); Table table = new Table(StandardBorderStyle.SINGLE_LINE); table.setWidth(new Width(TableWidthUnit.PERCENT, 100)); // First row - header spanning all columns Run headerRun = new Run(); headerRun.addText("Merged Header Cell (spans 3 columns)"); Paragraph headerPara = new Paragraph(); headerPara.add(headerRun); Cell headerCell = new Cell(); headerCell.add(headerPara); CellProperties headerProps = new CellProperties(); headerProps.setHorizontallyMergedCell(new HorizontallyMergedCell(MergeCellType.RESTART)); headerCell.setCellProperties(headerProps); Cell emptyCell1 = new Cell(); CellProperties emptyProps1 = new CellProperties(); emptyProps1.setHorizontallyMergedCell(new HorizontallyMergedCell(MergeCellType.CONTINUE)); emptyCell1.setCellProperties(emptyProps1); Cell emptyCell2 = new Cell(); CellProperties emptyProps2 = new CellProperties(); emptyProps2.setHorizontallyMergedCell(new HorizontallyMergedCell(MergeCellType.CONTINUE)); emptyCell2.setCellProperties(emptyProps2); Row headerRow = new Row(); headerRow.add(headerCell); headerRow.add(emptyCell1); headerRow.add(emptyCell2); // Second row - normal cells Cell cell1 = createCell("Column 1"); Cell cell2 = createCell("Column 2"); Cell cell3 = createCell("Column 3"); Row dataRow = new Row(); dataRow.add(cell1); dataRow.add(cell2); dataRow.add(cell3); table.add(headerRow); table.add(dataRow); doc.getBody().add(table); doc.save("c:\\test\\output.docx", true); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private static Cell createCell(String text) { Run run = new Run(); run.addText(text); Paragraph para = new Paragraph(); para.add(run); Cell cell = new Cell(); cell.add(para); return cell; } }
Need help? Ask our developers:
Name*
Email*
Message*