word文档的正文和表格中都可以包含图片,我们已经介绍过如何,这篇文章将介绍如何提取表格中的图片。
原文档如下:
c#
using system;
using spire.doc;
using spire.doc.documents;
using spire.doc.fields;
namespace extract_images_from_tables_in_word
{
class program
{
static void main(string[] args)
{
//创建document实例
document doc = new document();
//加载word文档
doc.loadfromfile("sample.docx");
//获取文档中第一个节
section section = doc.sections[0];
//调用extractimagesfromtables方法,提取表格中的图片
extractimagesfromtables(section);
//关闭
doc.close();
}
//创建静态方法extractimagesfromtables,参数为section对象
static void extractimagesfromtables(section section)
{
int index = 0;
string imagename = null;
//遍历section中的表格,提取表格中的图片并保存到本地
foreach (table table in section.tables)
{
for (int i = 0; i < table.rows.count; i )
{
for (int j = 0; j < table.rows[i].cells.count; j )
{
foreach (paragraph para in table[i, j].paragraphs)
{
foreach (documentobject obj in para.childobjects)
{
if (obj is docpicture)
{
imagename = string.format(@"images\tableimage-{0}.png", index);
(obj as docpicture).image.save(imagename, system.drawing.imaging.imageformat.png);
index ;
}
}
}
}
}
}
}
}
}
vb.net
imports system
imports spire.doc
imports spire.doc.documents
imports spire.doc.fields
namespace extract_images_from_tables_in_word
class program
private shared sub main(byval args() as string)
'创建document实例
dim doc as document = new document
'加载word文档
doc.loadfromfile("sample.docx")
'获取文档中第一个节
dim section as section = doc.sections(0)
'调用extractimagesfromtables方法,提取表格中的图片
program.extractimagesfromtables(section)
'关闭
doc.close
end sub
'创建静态方法extractimagesfromtables,参数为section对象
private shared sub extractimagesfromtables(byval section as section)
dim index as integer = 0
dim imagename as string = nothing
'遍历section中的表格,提取表格中的图片并保存到本地
for each table as table in section.tables
dim i as integer = 0
do while (i < table.rows.count)
dim j as integer = 0
do while (j < table.rows(i).cells.count)
for each para as paragraph in table(i, j).paragraphs
for each obj as documentobject in para.childobjects
if (typeof obj is docpicture) then
imagename = string.format("images\tableimage-{0}.png", index)
ctype(obj,docpicture).image.save(imagename, system.drawing.imaging.imageformat.png)
index = (index 1)
end if
next
next
j = (j 1)
loop
i = (i 1)
loop
next
end sub
end class
end namespace
效果图: