先要配置環境:
下載地址:
1,Free Spire.Doc for Java 下載網址:https://www.e-iceblue.cn/Downloads/Free-Spire-Doc-JAVA.html
2,因為我的是java 9.0 所以運行代碼的時候會報一些錯誤:網上的解決辦法大多是要降版本,但是我認為還是添加jar包更容易
jar包下載地址:https://github.com/Smartisa/JAR/tree/master/word文檔
上代碼:
1 package util; 2 import com.spire.doc.*; 3 4 import com.spire.doc.documents.HorizontalAlignment; 5 6 import com.spire.doc.documents.Paragraph; 7 8 import com.spire.doc.documents.ParagraphStyle; 9 10 11 12 import java.awt.*; 13 14 15 16 public class createWord { 17 18 public static void main(String[] args){ 19 20 //創建Word文檔 21 22 Document document = new Document(); 23 24 25 26 //添加一個section 27 28 Section section = document.addSection(); 29 30 31 32 //添加三個段落至section 33 34 Paragraph para1 = section.addParagraph(); 35 36 para1.appendText("虛擬機"); 37 38 39 40 Paragraph para2 = section.addParagraph(); 41 42 para2.appendText("虛擬機(Virtual Machine)指通過 軟件模擬的具有完整 硬件系統功能的、運行在一個完全 隔離環境中的完整 計算機系統。在實體計算機中能夠完成的工作在虛擬機中都能夠實現。在 計算機中創建虛擬機時,需要將實體機的部分硬盤和內存容量作為虛擬機的硬盤和內存容量。每個虛擬機都有獨立的 CMOS、硬盤和 操作系統,可以像使用實體機一樣對虛擬機進行操作。 [1] "); 43 44 45 46 Paragraph para3 = section.addParagraph(); 47 48 para3.appendText("網址: https://baike.baidu.com/item/%E8%99%9A%E6%8B%9F%E6%9C%BA"); 49 50 51 52 //將第一段作為標題,設置標題格式 53 54 ParagraphStyle style1 = new ParagraphStyle(document); 55 56 style1.setName("titleStyle"); 57 58 style1.getCharacterFormat().setBold(true); 59 60 style1.getCharacterFormat().setTextColor(Color.BLUE); 61 62 style1.getCharacterFormat().setFontName("宋體"); 63 64 style1.getCharacterFormat().setFontSize(12f); 65 66 document.getStyles().add(style1); 67 68 para1.applyStyle("titleStyle"); 69 70 71 72 //設置其余兩個段落的格式 73 74 ParagraphStyle style2 = new ParagraphStyle(document); 75 76 style2.setName("paraStyle"); 77 78 style2.getCharacterFormat().setFontName("宋體"); 79 80 style2.getCharacterFormat().setFontSize(11f); 81 82 document.getStyles().add(style2); 83 84 para2.applyStyle("paraStyle"); 85 86 para3.applyStyle("paraStyle"); 87 88 89 90 //設置第一個段落的對齊方式 91 92 para1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); 93 94 95 96 //設置第二段和第三段的段首縮進 97 98 para2.getFormat().setFirstLineIndent(25f); 99 100 para3.getFormat().setFirstLineIndent(25f); 101 102 103 104 //設置第一段和第二段的段后間距 105 106 para1.getFormat().setAfterSpacing(15f); 107 108 para2.getFormat().setAfterSpacing(10f); 109 110 111 112 //保存文檔 113 114 document.saveToFile("E:\\IDEA\\WorkSpace\\熱詞\\Output.docx", FileFormat.Docx); 115 116 } 117 118 }
直接運行就可以用了