java生成word表格文档
时间: 2023-08-15 11:08:02 浏览: 133
要使用Java生成Word表格文档,可以使用Apache POI库中的XWPFDocument类和XWPFTable类来完成。
以下是一个简单的示例代码,演示如何生成一个包含数据的表格:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xwpf.usermodel.*;
public class WordTableExample {
public static void main(String[] args) throws IOException {
//创建新的Word文档
XWPFDocument document = new XWPFDocument();
//创建一个带有3行、4列的表格
XWPFTable table = document.createTable(3, 4);
//给表格设置标题行,并填充数据
XWPFTableRow headerRow = table.getRow(0);
headerRow.getCell(0).setText("姓名");
headerRow.getCell(1).setText("年龄");
headerRow.getCell(2).setText("性别");
headerRow.getCell(3).setText("地址");
//填充表格数据
table.getRow(1).getCell(0).setText("张三");
table.getRow(1).getCell(1).setText("25");
table.getRow(1).getCell(2).setText("男");
table.getRow(1).getCell(3).setText("北京");
table.getRow(2).getCell(0).setText("李四");
table.getRow(2).getCell(1).setText("30");
table.getRow(2).getCell(2).setText("女");
table.getRow(2).getCell(3).setText("上海");
//将文档保存到本地
FileOutputStream out = new FileOutputStream("table.docx");
document.write(out);
out.close();
System.out.println("Word文档已生成!");
}
}
```
运行上述代码后,将会生成一个名为“table.docx”的Word文档,其中包含一个带有数据的表格。
阅读全文
相关推荐













