本文介绍如何使用spire.doc for java来读取word表格中的文本数据和图片。
用于测试的word文档如下:
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);
}
}
}
文本数据读取结果:
图片读取结果: