您好,欢迎来到华佗健康网。
搜索
您的当前位置:首页Java读取txt文件生成Word文档

Java读取txt文件生成Word文档

来源:华佗健康网
Java读取txt⽂件⽣成Word⽂档

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

IntelliJ IDEATxt⽂档

导⼊Jar包

两种⽅法可在Java程序中导⼊jar⽂件1. 。

在pom.xml中配置如下:

com.e-iceblue

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

e-iceblue spire.doc.free 3.9.0

2. ⼿动导⼊。

需先下载 到本地,解压,找到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\ doc.dispose(); }}

Word创建结果:

注意事项

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

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo0.com 版权所有 湘ICP备2023021991号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务