在本教程中,我们将学习如何使用 Java 创建 Word 文档。您可以创建 DOC 或 DOCX 格式的文件,其中可以包含文本内容以及图像。以下步骤可用于使用 java 创建 Word 文档,只需几个简单的步骤。
使用 Java 创建 Word 文档的步骤
- 从 Maven 存储库安装 Aspose.Words for Java
- 使用 Document 类对象创建一个空白 Word 文档
- 初始化 DocumentBuilder 类的新对象"
- 插入由边框包围的文本字符串
- 插入超链接
- 保存 Word 文档
这些简单的步骤配置所需的库,然后初始化 Document 类以创建一个空文档。然后它插入带有超链接的文本并继续在 Java 中创建 Word 文档。
使用 Java 生成 Word 文档的代码
import com.aspose.words.License; | |
import com.aspose.words.Document; | |
import com.aspose.words.DocumentBuilder; | |
public class CreateWordDocumentUsingJava { | |
public static void main(String[] args) throws Exception { //main function for CreateWordDocumentUsingJava | |
// Initialize a license to avoid trial version watermark in the output Word file | |
License license = new License(); | |
license.setLicense("Aspose.Words.lic"); | |
// Create a blank Word document file | |
Document doc = new Document(); | |
// Initialize a new object of DocumentBuilder class | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// Insert a text string surrounded by a border | |
builder.getFont().getBorder().setColor(java.awt.Color.BLACK); | |
builder.getFont().getBorder().setLineWidth(2.5d); | |
builder.getFont().getBorder().setLineStyle(com.aspose.words.LineStyle.DASH_DOT_STROKER); | |
builder.write("Text surrounded by black border."); | |
// Remove all font formatting specified explicitly | |
builder.getFont().clearFormatting(); | |
builder.insertBreak(com.aspose.words.BreakType.PARAGRAPH_BREAK); | |
builder.write("For further information, please visit the "); | |
// Insert a hyperlink and emphasize it with custom formatting | |
builder.getFont().setColor(java.awt.Color.BLUE); | |
builder.getFont().setUnderline(com.aspose.words.Underline.SINGLE); | |
builder.insertHyperlink("Aspose Knowledge Base", "https://kb.aspose.com/", false); | |
builder.getFont().clearFormatting(); | |
builder.writeln("."); | |
// Save the document with compliance level | |
doc.save("WordDocumentCreatedUsingJava.docx"); | |
} | |
} |
此 Java 代码片段无需安装任何文字处理应用程序(如 MS Word)即可创建 Word 文档。 使用 Java* 生成 Word 文档的功能与上述示例模拟了 MS Word 应用程序的行为,而不依赖于它。
在此示例中,我们探索了如何使用 Java 创建 Word 文档。此外,如果您想了解如何从 HTML 格式生成 PDF 文件,请参阅 如何在 Java 中从 HTML 生成 PDF 上的文章。