本文通過Java程式來展示如何讀取Word表格,包括讀取表格中的文本和圖片,下面是具體實作的步驟和方法,
1. 程式環境準備
- 代碼編譯工具:IntelliJ IDEA
- Jdk版本:1.8.0
- 測驗檔案:Word .docx 2013
- Jar包:free spire.doc.jar 3.9.0
用于測驗的Word檔案如下:

Jar匯入步驟及方法:
方法1:手動匯入,打開Project Structure(Shift+Ctrl+Alt+S)界面,選擇【Modules】—【Dependencies】,點擊“+”,【JARs or directories…】,選擇本地路徑中的jar包,添加后,勾選,點擊“OK”或者“Apply”匯入jar,

方法2:Maven倉庫匯入,需在pom.xml檔案中配置maven路徑并指定free spire.doc.jar 3.9.0的依賴,然后下載匯入,具體配置如下:
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>http://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>free.spire.doc</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
2. Java代碼
import com.spire.doc.*; import com.spire.doc.documents.Paragraph; import com.spire.doc.fields.DocPicture; import com.spire.doc.interfaces.ITable; import javax.imageio.ImageIO; import java.awt.image.RenderedImage; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class GetTable { public static void main(String[] args)throws IOException { //加載Word測驗檔案 Document doc = new Document(); doc.loadFromFile("inputfile.docx"); //獲取第一節 Section section = doc.getSections().get(0); //獲取第一個表格 ITable table = section.getTables().get(0); //創建txt檔案(用于寫入表格中提取的文本) String output = "ReadTextFromTable.txt"; File textfile = new File(output); if (textfile.exists()) { textfile.delete(); } textfile.createNewFile(); FileWriter fw = new FileWriter(textfile, true); BufferedWriter bw = new BufferedWriter(fw); //創建List List images = new ArrayList(); //遍歷表格中的行 for (int i = 0; i < table.getRows().getCount(); i++) { TableRow row = table.getRows().get(i); //遍歷每行中的單元格 for (int j = 0; j < row.getCells().getCount(); j++) { TableCell cell = row.getCells().get(j); //遍歷單元格中的段落 for (int k = 0; k < cell.getParagraphs().getCount(); k++) { Paragraph paragraph = cell.getParagraphs().get(k); bw.write(paragraph.getText() + "\t");//獲取文本內容 //遍歷段落中的所有子物件 for (int x = 0; x < paragraph.getChildObjects().getCount(); x++) { Object object = paragraph.getChildObjects().get(x); //判定物件是否為圖片 if (object instanceof DocPicture) { //獲取圖片 DocPicture picture = (DocPicture) object; images.add(picture.getImage()); } } } } bw.write("\r\n");//寫入內容到txt檔案 } bw.flush(); bw.close(); fw.close(); //將圖片以PNG檔案格式保存 for (int z = 0; z < images.size(); z++) { File imagefile = new File(String.format("提取的表格圖片-%d.png", z)); ImageIO.write((RenderedImage) images.get(z), "PNG", imagefile); } } }
3. 文本、圖片讀取效果
完成代碼編輯后,執行程式,讀取表格中的文本資料和圖片,代碼中的檔案路徑為IDEA專案檔案夾路徑,如:
C:\Users\Administrator\IdeaProjects\Table_Doc\ReadTextFromTable.txt
C:\Users\Administrator\IdeaProjects\Table_Doc\提取的表格圖片-0.png
C:\Users\Administrator\IdeaProjects\Table_Doc\inputfile.docx
在代碼中,檔案路徑可自定義為其他路徑,
文本資料讀取結果:

圖片讀取結果:

—End—
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/288861.html
標籤:其他
