隐藏

Spire.XLS教程从C#的Excel形状中提取文本和图像

发布:2023/3/22 16:09:06作者:管理员 来源:本站 浏览次数:280

一个excel形状可以用文字或图像填充,有时我们需要读取形状中的文字和图像信息。 在本文中,我们将介绍如何使用Spire.XLS和C#从Excel中的形状中提取文本和图像。


以下是我们用于演示的示例文档的屏幕截图:


详细步骤:


Step 1: 初始化Workbook类的对象并加载Excel文件。


   Workbook workbook = new Workbook();

   workbook.LoadFromFile("Input.xlsx");


Step 2: 获取第一张工作表。


Worksheet sheet = workbook.Worksheets[0];


Step 3: 从第一个形状中提取文本并保存到txt文件。


   IPrstGeomShape shape1 = sheet.PrstGeomShapes[0];

   string s = shape1.Text;

   StringBuilder sb = new StringBuilder();

   sb.AppendLine(s);

   File.WriteAllText("ShapeText.txt", sb.ToString());


Step 4: 从第二个形状中提取图像并保存到本地文件夹。


   IPrstGeomShape shape2 = sheet.PrstGeomShapes[1];

   Image image = shape2.Fill.Picture;

   image.Save(@"Image\ShapeImage.png", ImageFormat.Png);


截图:


提取的文本:


提取的图像:


完整代码:


   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);

           }

       }

   }