使用 Java 代码自动生成 Word 文档,可以帮助开发者高效完成报告生成、发票制作等文档处理工作。在 Spire.Doc for Java 的帮助下,你无需依赖 Microsoft Office,就能在应用程序中动态创建、格式化并自定义 Word 文件,实现更高效的文档自动化。 本文将带你一步步完成从零生成 Word 文档的关键流程,包括文字格式设置、图片插入、表格创建以及列表管理等内容。无论是编写业务报告、合同,还是处理数据驱动的文档,本教程都能为你提供一个清晰实用的入门指南,助你轻松实现 Java 环境下的文档自动化。
安装 Spire.Doc for Java
首先,您需要在 Java 程序中添加 Spire.Doc.jar 文件作为依赖项。您可以下载 JAR 文件;如果您使用 Maven,则可以通过在 pom.xml 文件中添加以下代码导入 JAR 文件。
<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>13.10.6</version>
    </dependency>
</dependencies>
在 Java 中向 Word 文档添加标题、章节和段落
使用 Spire.Doc for Java 创建结构化的 Word 文档时,核心功能主要围绕 Document 和 Section 类展开。通过 addParagraph() 方法,你可以向文档中添加段落;使用 appendText() 方法则可以插入文本内容。为了实现专业、统一的排版效果,你还可以应用内置样式(如 Title 或 Heading 1–4)。同时,Spire.Doc 还支持自定义样式,灵活控制字体、颜色和大小,为你打造个性化的文档风格。
在 Java 中向 Word 文档添加标题、章节和段落的基本步骤如下:
- 创建 Document 对象;
 - 使用 Document.addSection() 方法添加文档节;
 - 使用 Section.addParagraph() 方法向节中添加段落;
 - 使用 Paragraph.applyStyle() 方法为指定段落应用内置样式(如 Title、Heading1、Heading2、Heading3);
 - 通过 ParagraphStyle() 定义自定义段落样式,并将其应用到目标段落;
 - 将文档保存为 DOCX 文件格式。
 
import com.spire.doc.*;  
import com.spire.doc.documents.*;  
import com.spire.doc.fields.*;  
import java.awt.Color;  
  
public class CreateSimpleDocument {  
    public static void main(String[] args) {  
          
        // 创建一个 Document 类的对象  
        Document document = new Document();  
  
        // 添加节  
        Section section = document.addSection();  
          
        // 设置页边距  
        section.getPageSetup().getMargins().setAll(60f);  
          
        // 添加文档标题段落  
        Paragraph title_para = section.addParagraph();  
        TextRange textRange = title_para.appendText("这是标题");  
        title_para.applyStyle(BuiltinStyle.Title);  
        textRange.getCharacterFormat().setFontName("FangSong");  
          
        // 添加标题段落  
        Paragraph heading_one = section.addParagraph();  
        textRange = heading_one.appendText("一级标题");  
        heading_one.applyStyle(BuiltinStyle.Heading_1);  
        textRange.getCharacterFormat().setFontName("Times New Roman");  
          
        Paragraph heading_two = section.addParagraph();  
        textRange = heading_two.appendText("二级标题");  
        heading_two.applyStyle(BuiltinStyle.Heading_2);  
        textRange.getCharacterFormat().setFontName("Times New Roman");  
          
        Paragraph heading_three = section.addParagraph();  
        textRange = heading_three.appendText("三级标题");  
        heading_three.applyStyle(BuiltinStyle.Heading_3);  
        textRange.getCharacterFormat().setFontName("Times New Roman");  
          
        Paragraph heading_four = section.addParagraph();  
        textRange = heading_four.appendText("四级标题");  
        heading_four.applyStyle(BuiltinStyle.Heading_4);  
        textRange.getCharacterFormat().setFontName("Times New Roman");  
  
        // 添加普通段落  
        Paragraph normal_para = section.addParagraph();  
        normal_para.appendText("这是一个样本段落");  
          
        // 创建一个段落样式  
        ParagraphStyle style = new ParagraphStyle(document);  
        style.setName("paraStyle");  
        style.getCharacterFormat().setFontName("Times New Roman");  
        style.getCharacterFormat().setFontSize(13f);  
        style.getCharacterFormat().setTextColor(Color.blue);  
        document.getStyles().add(style);  
          
        // 应用自定义样式  
        normal_para.applyStyle("paraStyle");  
  
        // 保存文档  
        document.saveToFile("E:/Administrator/Python1/output/AddText.docx", FileFormat.Docx);  
        document.dispose();  
    }  
}

在 Java 中向 Word 文档插入图片
要想在 Word 文档中插入图片,通常需要先创建一个专用的段落作为图片的容器。然后通过 appendPicture() 方法,从本地文件系统加载图片,并将其直接嵌入到文档结构中。
在 Java 中向 Word 文档插入图片的步骤如下:
- 创建一个 Document 对象;
 - 使用 Document.addSection() 方法添加一个节;
 - 通过 Section.addParagraph() 方法向该节添加段落;
 - 使用 Paragraph.appendPicture() 方法将图片插入到段落中;
 - 将文档保存为 DOCX 文件格式。
 
import com.spire.doc.*;  
import com.spire.doc.documents.*;  
  
import javax.imageio.ImageIO;  
import java.awt.image.BufferedImage;  
import java.io.File;  
import java.io.IOException;  
  
public class AddImage {  
    public static void main(String[] args) throws IOException {  
          
        // 创建一个 Document 类的对象  
        Document document = new Document();  
          
        // 添加节  
        Section section = document.addSection();  
  
        // 设置页边距  
        section.getPageSetup().getMargins().setAll(60f);  
          
        // 添加段落  
        Paragraph image_para = section.addParagraph();  
          
        // 加载图片文件  
        BufferedImage image =  ImageIO.read(new File("F:/备用图片/Logo1.png"));  
  
        // 将图片添加到段落中  
        image_para.appendPicture(image);  
  
        // 保存文档  
        document.saveToFile("E:/Administrator/Python1/output/AddImage.docx", FileFormat.Docx);  
        document.dispose();  
    }  
}

在 Java 中向 Word 文档添加表格
创建表格的过程并不复杂,先调用 addTable() 方法建立表格的基本结构。接着,通过 resetCells() 方法指定表格的行数和列数。当表格结构初始化完成,就可以通过 addParagraph() 方法为每个单元格添加段落元素,并使用 appendText() 方法填充文本内容。
在 Java 中向 Word 文档添加表格的具体步骤如下:
- 创建 Document 对象;
 - 使用 Document.addSection() 方法添加一个节;
 - 创建一个二维数组用于存储表格数据(包括表头和单元格内容);
 - 使用 Section.addTable() 方法生成表格;
 - 调用 Table.resetCells() 方法,根据数据设置表格的行数和列数;
 - 遍历数据数组,使用 TableCell.addParagraph() 和 Paragraph.appendText() 方法将文本内容填充到各个单元格中;
 - 将文档保存为 DOCX 文件格式。
 
import com.spire.doc.*;  
import com.spire.doc.documents.*;  
import com.spire.doc.fields.*;  
    
public class AddTable {  
    public static void main(String[] args) {  
    
        // 创建一个 Documennt 类的实例  
        Document document = new Document();    
  
        // 添加一个节  
        Section section = document.addSection();    
  
        // Set page margins 设置页边距  
        section.getPageSetup().getMargins().setAll(60f);    
  
        // 定义表格数据为二维数组  
        String[][] data = {  
                {"产品", "单价", "数量", "总价"},  
                {"1", "¥29", "120", "¥3480"},  
                {"2", "¥35", "110", "¥3850"},  
                {"3", "¥68", "140", "¥9520"}  
        };  
    
        // 添加一个表格  
        Table table = section.addTable(true);  
    
        // 设置行数和列数  
        table.resetCells(data.length, data[0].length);    
  
        // 将数据写入单元格  
        for (int r = 0; r < data.length; r++) {  
            TableRow row = table.getRows().get(r);  
            row.setHeight(20);  
            row.setHeightType(TableRowHeightType.Exactly);   
  
            for (int c = 0; c < data[r].length; c++) {  
                TableCell cell = row.getCells().get(c);                  cell.getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);  
                TextRange textRange = cell.addParagraph().appendText(data[r][c]);  
                textRange.getCharacterFormat().setFontName("Times New Roman");  
                textRange.getCharacterFormat().setFontSize(14);  
            }  
        }    
  
        // 自动调整表格列宽以适应内容  
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);    
  
        // 保存文档  
        document.saveToFile("E:/Administrator/Python1/output/AddTable.docx", FileFormat.Docx);  
        document.dispose();  
    }  
}

在 Java 中向 Word 文档添加列表
如果你想在 Word 文档中添加项目符号列表或编号列表,可以借助 ListStyle 类来完成。通过配置该类,可以为所有列表项设定统一的视觉样式。当定义好列表样式,只需使用 applyStyle() 方法将其应用到目标段落,即可生成自定义样式的列表结构。
在 Java 中向 Word 文档添加列表的步骤如下:
- 创建 Document 对象;
 - 使用 Document.addSection() 方法添加一个节;
 - 通过 ListStyle() 定义列表样式(项目符号或编号);
 - 使用 Section.addParagraph() 方法向文档添加段落;
 - 调用 Paragraph.getListFormat().applyStyle() 方法,将定义好的列表样式应用到各个段落上;
 - 将文档保存为 DOCX 文件格式。
 
import com.spire.doc.*;  
import com.spire.doc.documents.*;  
import com.spire.doc.fields.*;  
  
public class AddList {  
    public static void main(String[] args) {  
  
        // 创建一个 Document类的对象  
        Document document = new Document();  
  
        // 添加节  
        Section section = document.addSection();  
  
        // 设置页边距  
        section.getPageSetup().getMargins().setAll(60f);  
  
        // 创建带符号的列表样式  
        ListStyle listStyle = new ListStyle(document, ListType.Bulleted);  
        listStyle.setName("bulletedList");  
        listStyle.getLevels().get(0).setBulletCharacter("\u00B7");  
        listStyle.getLevels().get(0).getCharacterFormat().setFontName("Symbol");  
        listStyle.getLevels().get(0).setTextPosition(20);  
        document.getListStyles().add(listStyle);  
  
        // 添加段落  
        Paragraph paragraph = section.addParagraph();  
        TextRange textRange = paragraph.appendText("水果:");  
        paragraph.getFormat().setAfterSpacing(5f);  
        textRange.getCharacterFormat().setFontName("Times New Roman");  
        textRange.getCharacterFormat().setFontSize(14);  
  
        // 添加4个段落作为带符号的列表项  
        String[] fruits = {"苹果", "香蕉", "西瓜", "芒果"};  
        for (String fruit : fruits) {  
            paragraph = section.addParagraph();  
            textRange = paragraph.appendText(fruit);  
            paragraph.getListFormat().applyStyle(listStyle.getName());  
            paragraph.getListFormat().setListLevelNumber(0);  
            textRange.getCharacterFormat().setFontName("Times New Roman");  
            textRange.getCharacterFormat().setFontSize(14);  
        }  
  
        // 保存文档  
        document.saveToFile("E:/Administrator/Python1/output/AddList.docx", FileFormat.Docx);  
        document.dispose();  
    }  
}

总结
本教程简要介绍了使用 Spire.Doc for Java 创建 Word 文档的基础操作,包括插入标题、段落、图片、表格和列表等核心功能。如果你对此感兴趣,可以试用 Spire.Doc 的免费版本,如果你要处理更加复杂的工作或其它需求,也欢迎随时联系我们。
    


					



