这篇文章将为大家详细讲解有关Java如何实现读取txt文件内容并生成Word文档,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
两种方法可在Java程序中导入jar文件
在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>
需先下载jar包到本地,解压,找到lib路径下的jar文件。然后在Java程序中打开“Project Structure”窗口,然后执行如下步骤导入:
找到本地路径下的jar文件,添加到列表,然后导入:
代码大致步骤如下:
实例化Document类的对象。然后通过Document.addSection()方法和Section.addParagraph()方法添加节和段落。
读取txt文件:创建InputStreamReader类的对象,构造方法中传递输入流和指定的编码表名称。通过BufferedReader类,创建字符流缓冲区。将读取的txt内容通过Paragraph.appendText()方法添加到段落。
调用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文档就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。