Java怎么实现读取txt文件内容并生成Word文档

本文将以Java程序代码为例介绍如何读取txt文件中的内容,生成Word文档。在编辑代码前,可参考如下代码环境进行配置:

导入Jar包

两种方法可在Java程序中导入jar文件

1. Maven仓库下载导入

在pom.xml中配置如下:

<repositories>

      <repository>

          <id>com.e-iceblue</id>

          <url>https://repo.e-iceblue.cn/repository/maven-public/</url>

      </repository>

  </repositories>

<dependencies>

  <dependency>

      <groupId>e-iceblue</groupId>

      <artifactId>spire.doc.free</artifactId>

      <version>3.9.0</version>

  </dependency>

</dependencies>

2. 手动导入

需先下载jar包到本地,解压,找到lib路径下的jar文件。然后在Java程序中打开“Project Structure”窗口,然后执行如下步骤导入:

找到本地路径下的jar文件,添加到列表,然后导入:

 

读取txt生成Word

代码大致步骤如下:

  1. 实例化Document类的对象。然后通过Document.addSection()方法和Section.addParagraph()方法添加节和段落。
  2. 读取txt文件:创建InputStreamReader类的对象,构造方法中传递输入流和指定的编码表名称。通过BufferedReader类,创建字符流缓冲区。将读取的txt内容通过Paragraph.appendText()方法添加到段落。
  3. 调用Document.saveToFile(string fileName, FileFormat fileFormat)方法保存为Word文档。
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;

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

public class ReadTextAndCreateWord {
  public static void main(String[] args) throws IOException {
      //实例化Document类的对象,并添加section和paragraph
      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.BLUE);
      style.getCharacterFormat().setFontName("幼圆");
      style.getCharacterFormat().setFontSize(12);
      doc.getStyles().add(style);
      paragraph.applyStyle("newstyle");
      paragraph.getFormat().setMirrorIndents(true);

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

Word创建结果:

 

注意事项

代码中的txt文件和word保存路径为IDEA程序项目文件夹路,如:F:\IDEAProject\CreateWord_Doc\addTxttoWord.docx ,文件路径可定义为其他路径。 

关于Java如何实现读取txt文件内容并生成Word文档的文章就介绍至此,更多相关Java 读取txt内容生成Word内容请搜索编程宝库以前的文章,希望以后支持编程宝库

解决mybatisplus @Select注解中拼写动态sql异常问题:mybatisplus 使用@Select时,之前一直用实体类传递参数,完全能够正常使用,今天换成了参数传递,报下面的错误:  @Select("<sc ...