讀取txt文件中的內容,生成Word文檔


1、maven引入

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

 

2、代碼

package com.example.study20211111;

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;

import java.awt.*;
import java.io.*;

/**
 *讀取txt文件中的內容,生成Word文檔
 */
public class ReadTextAndCreateWord {
    public static void main(String[] args) throws IOException {
        Document doc = new Document();
        Section section = doc.addSection();
        Paragraph paragraph = section.addParagraph();

        //讀取txt文件
        String encoding = "GBK";
        File file = new File("test.txt");
        if (file.isFile() && file.exists()) {
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encoding);
            BufferedReader bufferedReader = new BufferedReader(isr);
            String lineTXT;
            while ((lineTXT = bufferedReader.readLine()) != null) {
                paragraph.appendText(lineTXT);//在段落中寫入txt內容
            }
            isr.close();
        }
        //設置段落樣式,並應用到段落
        ParagraphStyle style = new ParagraphStyle(doc);
        style.setName("newstyle");
        style.getCharacterFormat().setBold(true);
        style.getCharacterFormat().setTextColor(Color.black);
        style.getCharacterFormat().setFontName("幼圓");
        style.getCharacterFormat().setFontSize(12);
        doc.getStyles().add(style);
        paragraph.applyStyle("newstyle");
        paragraph.getFormat().setMirrorIndents(true);

        //保存為docx格式的Word
        doc.saveToFile("test.docx", FileFormat.Docx_2013);
        doc.dispose();
    }
}

3、運行結果

text文檔內容:

 

 運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM