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
效果图: