HWPFDocument创建表格 完整代码
时间: 2023-07-09 07:52:32 浏览: 169
下面是使用 Apache POI 库创建 Word 表格的示例代码:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class CreateTableInWord {
public static void main(String[] args) {
String fileName = "create_table.doc";
POIFSFileSystem fs = null;
try {
fs = new POIFSFileSystem();
HWPFDocument doc = new HWPFDocument(fs);
Range range = doc.getRange();
// 创建表格
Table table = range.insertTableBefore((short) 2, 3);
table.setBorders(true);
table.setTableAutoformat(TableAutoformat.CLASSIC_1);
// 往表格中添加内容
TableRow row = table.getRow(0);
row.getCell(0).getParagraph(0).insertAfter("姓名", null);
row.addNewTableCell().getParagraph(0).insertAfter("年龄", null);
row.addNewTableCell().getParagraph(0).insertAfter("性别", null);
row = table.getRow(1);
row.getCell(0).getParagraph(0).insertAfter("张三", null);
row.addNewTableCell().getParagraph(0).insertAfter("25", null);
row.addNewTableCell().getParagraph(0).insertAfter("男", null);
row = table.getRow(2);
row.getCell(0).getParagraph(0).insertAfter("李四", null);
row.addNewTableCell().getParagraph(0).insertAfter("28", null);
row.addNewTableCell().getParagraph(0).insertAfter("女", null);
// 保存文档
FileOutputStream out = new FileOutputStream(fileName);
doc.write(out);
out.close();
System.out.println("create_table.doc 文件创建成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们首先创建了一个空的 HWPFDocument 对象,然后获取文档范围 Range 对象,接着使用 Range 对象的 insertTableBefore() 方法创建了一个 2 行 3 列的表格,并设置了表格的边框和自动格式化样式。最后,我们向表格中添加了一些数据,并将文档保存到磁盘上。
请注意,这个示例中使用的是 HWPFDocument 对象,它只能读写旧版的 Word 文档(.doc),如果你需要读写新版的 Word 文档(.docx),需要使用 XWPFDocument 对象。