Java如何實現(xiàn)讀取txt文件內容并生成Word文檔
本文將以Java程序代碼為例介紹如何讀取txt文件中的內容,生成Word文檔。在編輯代碼前,可參考如下代碼環(huán)境進行配置:
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”窗口,然后執(zhí)行如下步驟導入:

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


讀取txt生成Word
代碼大致步驟如下:
- 實例化Document類的對象。然后通過Document.addSection()方法和Section.addParagraph()方法添加節(jié)和段落。
- 讀取txt文件:創(chuàng)建InputStreamReader類的對象,構造方法中傳遞輸入流和指定的編碼表名稱。通過BufferedReader類,創(chuàng)建字符流緩沖區(qū)。將讀取的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創(chuàng)建結果:

注意事項
代碼中的txt文件和word保存路徑為IDEA程序項目文件夾路,如:F:\IDEAProject\CreateWord_Doc\addTxttoWord.docx ,文件路徑可定義為其他路徑。?
到此這篇關于Java如何實現(xiàn)讀取txt文件內容并生成Word文檔的文章就介紹到這了,更多相關Java 讀取txt內容生成Word內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java設計模式之責任鏈模式(Chain of Responsibility模式)介紹
這篇文章主要介紹了Java設計模式之責任鏈模式(Chain of Responsibility模式)介紹,本文講解了如何使用責任鏈模式,并給出了4種使用實例,需要的朋友可以參考下2015-03-03
淺談SpringBoot中的Bean初始化方法?@PostConstruct
這篇文章主要介紹了SpringBoot中的Bean初始化方法?@PostConstruct,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
SpringBoot實現(xiàn)事件監(jiān)聽(異步執(zhí)行)的示例代碼
事件監(jiān)聽是一種機制,可以定義和觸發(fā)自定義的事件,以及在應用程序中注冊監(jiān)聽器來響應這些事件,本文主要介紹了SpringBoot實現(xiàn)事件監(jiān)聽(異步執(zhí)行)的示例代碼,感興趣的可以了解一下2024-08-08

