HWPF-POI: inserting table in word with java

和自甴很熟 提交于 2019-12-12 01:55:19

问题


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?


回答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();
            }
        }
    }


来源:https://stackoverflow.com/questions/28341881/hwpf-poi-inserting-table-in-word-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!