Reggy Budiana

Reggy Budiana

  • NA
  • 2
  • 4.1k

How To Convert Shape to Image From Excel using NPOI and C#?

Sep 14 2016 3:45 AM

I'm writting code to Get All Images including Shapes from Excel (.xls and xlsx) using C# and NPOI(ver 2.2.1) Library. The purpose is to get all images including shapes from selected Excel file and then save it to specified directory.

After a while trial-error and browse any references, i'm able to get all Image from Excel using this code (I put code for read xls format),

  1. var lst = workbook.GetAllPictures();  
  2. for (int i = 0; i < lst.Count; i++)  
  3. {  
  4.     var pic = (HSSFPictureData)lst[i];  
  5.     byte[] data = pic.Data;  
  6.   
  7.     /*Save Image From Byte[]*/  
  8. }  

But, i can't get the Shapes in Excel with that Code, so i'm trying to find any other method and finally i found some code that can get List of Images and Shapes that exist in Sheet of Excel,

here the snippet of code (also code for read xls format file),

  1. var dr = workbook.GetSheetAt(sht).DrawingPatriarch;  
  2. HSSFPatriarch pat = (HSSFPatriarch)dr;  
  3. var shape = pat.Children;  
  4. int i = 0;  
  5. foreach (var s in shape)  
  6. {  
  7.     string patType = s.GetType().ToString();  
  8.     switch (patType)  
  9.     {  
  10.         case "NPOI.HSSF.UserModel.HSSFSimpleShape":  
  11.             {  
  12.                 var simpleshape = (HSSFSimpleShape)s;  
  13.   
  14.                 /*Save Shape*/  
  15.   
  16.                 break;  
  17.             }  
  18.         case "NPOI.HSSF.UserModel.HSSFPicture":  
  19.             {  
  20.                 var pic = (HSSFPicture)s;  
  21.                 byte[] data = pic.PictureData.Data;  
  22.   
  23.                 /*Code to Save Image From Byte[]*/  
  24.   
  25.                 break;  
  26.             }  
  27.         defaultbreak;  
  28.     }  
  29. }  

And when i put breakpoint on foreach statement and watch, it's show the list of Images and Shapes that i need to Save.

With that code, I'm able to Get and Save its Image data (HSSFPicture), But I can't find any Method or Properties for Converting or Saving Shape Data (HSSFSimpleShape) to Image.

My Question is, How can I Convert this Shape data to Image, and saving it to specified directory? Is there something wrong with the code that I write? Or maybe there is another solution (using NPOI of course) that i can use to get Shapes from Excel (xls or xlsx) file?

 

Answers (1)