一個excel形狀能夠用文字或圖像填充,有時咱們須要讀取形狀中的文字和圖像信息。 在本文中,咱們將介紹如何使用Spire.XLS和C#從Excel中的形狀中提取文本和圖像。html
如下是咱們用於演示的示例文檔的屏幕截圖:ui
詳細步驟:spa
Step 1: 初始化Workbook類的對象並加載Excel文件。excel
Workbook workbook = new Workbook(); workbook.LoadFromFile("Input.xlsx");
Step 2: 獲取第一張工做表。orm
Worksheet sheet = workbook.Worksheets[0];
Step 3: 從第一個形狀中提取文本並保存到txt文件。htm
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);
截圖:blog
提取的文本:圖片
提取的圖像:文檔
完整代碼:
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); } } }