1. 程式人生 > 實用技巧 >Java 生成Word文件

Java 生成Word文件

Word具有強大的文書處理功能,是我們日常工作生活中廣泛使用到的工具之一。本文就將介紹如何使用Free Spire.Doc for Java在Java應用程式中建立Word文件,插入圖片,並且設定段落的字型格式、對齊方式、段首縮排以及段落間距等。

Jar包匯入

方法一:下載Free Spire.Doc for Java包並解壓縮,然後將lib資料夾下的Spire.Doc.jar包作為依賴項匯入到Java應用程式中。

方法二:通過Maven倉庫安裝JAR包,配置pom.xml檔案的程式碼如下

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <url>http://
repo.e-iceblue.cn/repository/maven-public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc.free</artifactId> <version>2.7.3</version> </dependency> </dependencies>

Java程式碼

import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;
import com.spire.doc.fields.DocPicture;

import java.awt.*;

public class CreateWordDocument {
    public static void main(String[] args){
        
//建立Word文件 Document document = new Document(); //新增一個section Section section = document.addSection(); //新增4個段落至section Paragraph para1 = section.addParagraph(); para1.appendText("滕王閣序"); Paragraph para2 = section.addParagraph(); para2.appendText("豫章故郡,洪都新府。星分翼軫,地接衡廬。襟三江而帶五湖,控蠻荊而引甌越。"+ "物華天寶,龍光射牛鬥之墟;人傑地靈,徐孺下陳蕃之榻。雄州霧列,俊採星馳。臺隍枕夷夏之交,賓主盡東南之美。"+ "都督閻公之雅望,棨戟遙臨;宇文新州之懿範,襜帷暫駐。十旬休假,勝友如雲;千里逢迎,高朋滿座。"+ "騰蛟起鳳,孟學士之詞宗;紫電青霜,王將軍之武庫。家君作宰,路出名區;童子何知,躬逢勝餞。"); Paragraph para3 = section.addParagraph(); para3.appendText("時維九月,序屬三秋。潦水盡而寒潭清,煙光凝而暮山紫。儼驂騑於上路,訪風景於崇阿;臨帝子之長洲,得天人之舊館。"+ "層巒聳翠,上出重霄;飛閣流丹,下臨無地。鶴汀鳧渚,窮島嶼之縈迴;桂殿蘭宮,即岡巒之體勢。"); //新增圖片 Paragraph para4 = section.addParagraph(); DocPicture picture = para4.appendPicture("C:\\Users\\Administrator\\Desktop\\1.jpg"); //設定圖片寬度 picture.setWidth(300f); //設定圖片高度 picture.setHeight(250f); //將第一段作為標題,設定標題格式 ParagraphStyle style1 = new ParagraphStyle(document); style1.setName("titleStyle"); style1.getCharacterFormat().setBold(true); style1.getCharacterFormat().setTextColor(Color.BLUE); style1.getCharacterFormat().setFontName("宋體"); style1.getCharacterFormat().setFontSize(12f); document.getStyles().add(style1); para1.applyStyle("titleStyle"); //設定其餘三個段落的格式 ParagraphStyle style2 = new ParagraphStyle(document); style2.setName("paraStyle"); style2.getCharacterFormat().setFontName("宋體"); style2.getCharacterFormat().setFontSize(11f); document.getStyles().add(style2); para2.applyStyle("paraStyle"); para3.applyStyle("paraStyle"); para4.applyStyle("paraStyle"); //設定第一個段落的對齊方式 para1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); //設定第二段和第三段的段首縮排 para2.getFormat().setFirstLineIndent(25f); para3.getFormat().setFirstLineIndent(25f); //設定第一段和第二段的段後間距 para1.getFormat().setAfterSpacing(15f); para2.getFormat().setAfterSpacing(10f); //將第四段的圖片設定為水平居中對齊方式 para4.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); //儲存文件 document.saveToFile("Output.docx", FileFormat.Docx); } }