当前位置:硬件测评 > Java读取txt文件生成Word文档

Java读取txt文件生成Word文档

  • 发布:2023-10-11 05:06

-->

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

  • IntelliJ IDEA
  • 用于 Java 的免费 Spire.Doc
  • txt文档

导入Jar包

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

1。下载并导入Maven仓库。

在pom.xml中配置如下:

com.e-iceblue https://www.sychzs.cn/repository/maven-public/ e-冰蓝 www.sychzs.cn 3.9.0

2。手动导入。

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

在本地路径中找到jar文件,将其添加到列表中,然后导入:

读取txt生成Word

代码大致步骤如下:

  1. 实例化类 Document 的对象。然后通过 Document.addSection() 方法和 Section.addParagraph() 方法添加章节和段落。
  2. 读取txt文件:创建InputStreamReader类的对象,并在构造函数中传入输入流和指定的编码表名称。通过BufferedReader类创建字符流缓冲区。通过Paragraph.appendText()方法将读取的txt内容添加到段落中。
  3. 调用Document.saveToFile(string fileName, FileFormat fileFormat)方法将其另存为Word文档。
导入 com.spire.doc.*;
导入 com.spire.doc.documents.Paragraph;
导入 com.spire.doc.documents.ParagraphStyle; 导入java.awt.*;
导入www.sychzs.cn.*; 公共类 ReadTextAndCreateWord {
public static void main(String[] args) 抛出 IOException {
//实例化Document类的对象,添加section和paragraph
文档 doc = new Document();
节节 = doc.addSection();
段落段落=section.addParagraph(); //读取txt文件
字符串编码 = "GBK";
文件 file = new File("test.txt");
if (file.isFile() && file.exists()) {
InputStreamReader isr = new InputStreamReader(new FileInputStream(文件), 编码);
BufferedReader bufferedReader = new BufferedReader(isr);
字符串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(www.sychzs.cn);
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();
}
}

造词结果:

注释

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

—结束—

-->

相关文章

最新资讯

热门推荐