天天看點

C# 提取Word文檔中的圖檔

C# 提取Word文檔中的圖檔

圖檔和文字是word文檔中兩種最常見的對象,在微軟word中,如果我們想要提取出一個文檔内的圖檔,隻需要右擊圖檔選擇另存為然後命名儲存就可以了,今天這篇文章主要是實作使用C#從word文檔中提取圖檔。

這裡我準備了一個含有文字和圖檔的word文檔:

C# 提取Word文檔中的圖檔

詳細步驟與代碼:

步驟1:添加引用。

建立一個Visual C#控制台項目,添加引用并使用如下命名空間:

using System;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
      

步驟2:建立一個word文檔對象并加載需要提取圖檔的word文檔。

Document document = new Document("法國景點.docx ");
      

步驟3:周遊文檔中的所有section,找到圖檔,将它們提取出來并儲存。

int index = 0;

//擷取文檔的section
foreach (Section section in document.Sections)
{
    //擷取section中的段落
    foreach (Paragraph paragraph in section.Paragraphs)
    {
        //擷取段落中的文檔對象
        foreach (DocumentObject docObject in paragraph.ChildObjects)
        {
            //對對象的type進行判斷,如果是圖檔,就提取出來
            if (docObject.DocumentObjectType == DocumentObjectType.Picture)
            {
                DocPicture picture = docObject as DocPicture; 
                //給圖檔命名
                String imageName = String.Format(@"images\Image-{0}.png", index); 
                //儲存圖檔
                picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png);
                index++;
            }
        }
    }
}
      

提取出來的圖檔:

C# 提取Word文檔中的圖檔

全部代碼:

using System;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace Extract_image_from_word
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document("法國景點.docx");

            int index = 0; 
            foreach (Section section in document.Sections)
            {
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    foreach (DocumentObject docObject in paragraph.ChildObjects)
                    {
                        if (docObject.DocumentObjectType == DocumentObjectType.Picture)
                        {
                            DocPicture picture = docObject as DocPicture;
                            String imageName = String.Format(@"images\Image-{0}.png", index); 
                            picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png);
                            index++;
                        }
                    }
                }
            }
        }
    }
}
      

總結:

這裡我使用的是E-iceblue公司的免費

word

元件,它除了可以從文檔中提取圖檔,還可以提取文本,這裡我隻寫了提取圖檔的,提取文本的也差不多,如有需要可以留言。