Java 读取txt文件生成Word文档
本文将以Java程序代码为例介绍如何读取txt文件中的内容,生成Word文档。在编辑代码前,可参考如下代码环境进行配置:
- IntelliJ IDEA
- Free Spire.Doc for Java
- Txt文档
导入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
代码大致步骤如下:
- 实例化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 ,文件路径可定义为其他路径。
—End—
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
2019-12-03 Java 添加Word形状或图形