Click here to Skip to main content
15,894,539 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.

My Problem is, I Can't find any method for Convert this Shape data from Excel 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?

What I have tried:

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

C#
var lst = workbook.GetAllPictures();
for (int i = 0; i < lst.Count; i++)
{
   var pic = (HSSFPictureData)lst[i];
   byte[] data = pic.Data;

   /*Save Image From Byte[]*/
}


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


C#
var dr = workbook.GetSheetAt(sht).DrawingPatriarch;
HSSFPatriarch pat = (HSSFPatriarch)dr;
var shape = pat.Children;
int i = 0;
foreach (var s in shape)
{
    string patType = s.GetType().ToString();
    switch (patType)
    {
        case "NPOI.HSSF.UserModel.HSSFSimpleShape":
            {
                var simpleshape = (HSSFSimpleShape)s;

                /*Save Shape*/

                break;
            }
        case "NPOI.HSSF.UserModel.HSSFPicture":
            {
                var pic = (HSSFPicture)s;
                byte[] data = pic.PictureData.Data;

                /*Code to Save Image From Byte[]*/

                break;
            }
        default: break;
    }
}


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.
Posted
Updated 13-Sep-16 21:07pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900