0

I want to create a table in Word with POI-HWPF (e.g. doc format). My example code is:

Table table = document.getRange().insertTableBefore((short) 2, 2);

The table is inserted, but I can't see it - as if the table has the width 0. Can anybody help me?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Louisa
  • 55
  • 10

1 Answers1

1

The file linked in this old bug report should give you an idea how to do it.

So in essence: You probably need to add some content (i.e. a paragraph in a cell) so that Word has something to render.

Here is the example code used in the bug report:

private static void test (int rows, int columns) throws Exception {
    // POI apparently can't create a document from scratch,
    // so we need an existing empty dummy document
    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("empty.doc"));
    HWPFDocument doc = new HWPFDocument(fs);

    Range range = doc.getRange();
    Table table = range.insertBefore(new TableProperties(columns), rows);

    for (int rowIdx=0; rowIdx<table.numRows(); rowIdx++) {
        TableRow row = table.getRow(rowIdx);
        System.out.println("row "+rowIdx);
        for (int colIdx=0; colIdx<row.numCells(); colIdx++) {
            TableCell cell = row.getCell(colIdx);
            System.out.println("column "+colIdx+", num paragraphs "+cell.numParagraphs());
            try {
                Paragraph par = cell.getParagraph(0);
                par.insertBefore(""+(rowIdx*row.numCells()+colIdx));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
kritzikratzi
  • 19,662
  • 1
  • 29
  • 40
morido
  • 1,027
  • 7
  • 24