Extract text and image from Excel shape in C#

An excel shape can be filled with text or image, sometimes we need to read the text and image information in the shape. In this article, we are going to introduce how to extract text and image from shapes in Excel using Spire.XLS and C#.

Below is the screenshot of the sample document we used for demonstration:

Extract text and image from Excel shape in C#

Detail steps:

Step 1: Initialize an object of Workbook class and Load the Excel file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xlsx");

Step 2: Get the first worksheet.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Extract text from the first shape and save to a txt file.

IPrstGeomShape shape1 = sheet.PrstGeomShapes[0];
string s = shape1.Text;
StringBuilder sb = new StringBuilder();
sb.AppendLine(s);
File.WriteAllText("ShapeText.txt", sb.ToString()); 

Step 4: Extract image from the second shape and save to a local folder.

IPrstGeomShape shape2 = sheet.PrstGeomShapes[1];
Image image = shape2.Fill.Picture;
image.Save(@"Image\ShapeImage.png", ImageFormat.Png);

Screeshot:

Extracted text:

Extract text and image from Excel shape in C#

Extracted image:

Extract text and image from Excel shape in C#

Full code:

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using Spire.Xls;
using Spire.Xls.Core;

namespace Extract_text_and_image_from_Excel_shape
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the Excel file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Input.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Extract text from the first shape and save to a txt file
            IPrstGeomShape shape1 = sheet.PrstGeomShapes[0];
            string s = shape1.Text;
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(s);
            File.WriteAllText("ShapeText.txt", sb.ToString()); 

            //Extract image from the second shape and save to a local folder
            IPrstGeomShape shape2 = sheet.PrstGeomShapes[1];
            Image image = shape2.Fill.Picture;
            image.Save(@"Image\ShapeImage.png", ImageFormat.Png);
        }
    }
}