读取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文档内容:

 

 运行结果:

 

posted @ 2021-12-03 16:48  猿先僧  阅读(703)  评论(0)    收藏  举报