Java可以使用Apache POI库来生成Word文档。以下是一个简单的示例:

  1. 添加依赖库

在项目的pom.xml文件中添加以下依赖:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
  1. 创建Word文档

使用以下代码创建一个空的Word文档:

XWPFDocument document = new XWPFDocument();
  1. 添加段落

使用以下代码添加一个段落到文档中:

XWPFParagraph paragraph = document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun run = paragraph.createRun();
run.setText("Hello World!");
run.setFontSize(18);
run.setBold(true);
  1. 添加表格

使用以下代码添加一个表格到文档中:

XWPFTable table = document.createTable();
table.setWidth("100%");
XWPFTableRow row = table.getRow(0);
row.getCell(0).setText("Name");
row.createCell().setText("Age");
row.createCell().setText("Gender");
XWPFTableRow row1 = table.createRow();
row1.getCell(0).setText("Tom");
row1.getCell(1).setText("25");
row1.getCell(2).setText("Male");
XWPFTableRow row2 = table.createRow();
row2.getCell(0).setText("Lucy");
row2.getCell(1).setText("22");
row2.getCell(2).setText("Female");
  1. 保存文档

使用以下代码将文档保存到文件中:

FileOutputStream out = new FileOutputStream("example.docx");
document.write(out);
out.close();
document.close();

完整的示例代码如下:

import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;

public class WordGenerator {
    public static void main(String[] args) throws Exception {
        XWPFDocument document = new XWPFDocument();

        // 添加段落
        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun run = paragraph.createRun();
        run.setText("Hello World!");
        run.setFontSize(18);
        run.setBold(true);

        // 添加表格
        XWPFTable table = document.createTable();
        table.setWidth("100%");
        XWPFTableRow row = table.getRow(0);
        row.getCell(0).setText("Name");
        row.createCell().setText("Age");
        row.createCell().setText("Gender");
        XWPFTableRow row1 = table.createRow();
        row1.getCell(0).setText("Tom");
        row1.getCell(1).setText("25");
        row1.getCell(2).setText("Male");
        XWPFTableRow row2 = table.createRow();
        row2.getCell(0).setText("Lucy");
        row2.getCell(1).setText("22");
        row2.getCell(2).setText("Female");

        // 保存文档
        FileOutputStream out = new FileOutputStream("example.docx");
        document.write(out);
        out.close();
        document.close();
    }
}
java生成word文件

原文地址: http://www.cveoy.top/t/topic/b0GO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录