HWPF-POI:用Java在Word中插入表格 [英] HWPF-POI: inserting table in word with java

查看:1382
本文介绍了HWPF-POI:用Java在Word中插入表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用POI-HWPF(例如doc格式)在Word中创建一个表. 我的示例代码是:

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);

表格已插入,但我看不到-好像表格的宽度为0. 有人可以帮我吗?

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

推荐答案

这个旧错误报告应该为您提供了一个解决方法.

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

所以从本质上讲:您可能需要添加一些内容(即单元格中的一个段落),以便Word可以呈现某些内容.

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

这篇关于HWPF-POI:用Java在Word中插入表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆