1
votes

I'm programming in C#.NET (VS 2017) using ClosedXML. And I have one Excel file like this:

 |  A   |    B    |   C   |   D 

1| Code |  Image  | Price | Others

2| PX1  | [IMAGE] | $0.25 | Text 

3| XYZ  | [IMAGE] | $0.58 | Descp

I can get all text and number cells, but when I want to get the value of image (B2 for example) I can't, C# returns an empty string :(...

How can I get image/s (pictures) from file?

I read about adding an image to the file, BUT, I want to get it, not add.

2

2 Answers

2
votes

Images (or rather pictures) are not saved in the cell but in the worksheet. You can get all pictures in a worksheet with worksheet.Pictures and a certain picture by name with worksheet.Pictures.Picture(name).

If you need pictures for cells you could build a dictionary with cell addresses and pictures:

Dictionary<IXLAddress, ClosedXML.Excel.Drawings.IXLPicture> PicturesByCellAddress
    = new Dictionary<IXLAddress, ClosedXML.Excel.Drawings.IXLPicture>();
foreach (ClosedXML.Excel.Drawings.IXLPicture pic in worksheet.Pictures)
{
    PicturesByCellAddress.Add(pic.TopLeftCellAddress, pic);
}
0
votes

Well, thanks to Raidri I can get all images for Worksheet, but, if someone wants to get image for row, I edited the code:

Dictionary<int, ClosedXML.Excel.Drawings.IXLPicture> PicturesByCellAddress
    = new Dictionary<int, ClosedXML.Excel.Drawings.IXLPicture>();
                    foreach (ClosedXML.Excel.Drawings.IXLPicture pic in hoja.Pictures)
                    {
                        try { PicturesByCellAddress.Add(pic.TopLeftCellAddress.RowNumber, pic); }
                        catch { }
                    }

And then, when I foreach every row for info, only use the number of row (Because I know the number of Column), but, If you change some cells in Excel, ClosedXML starts by the name of the picture, and sometimes starts at last row, for that, I need the row number.

Finally, convert to Image:

ClosedXML.Excel.Drawings.IXLPicture foto;
Image imagen;
try {
    foto = PicturesByCellAddress[i];
    imagen = Image.FromStream(foto.ImageStream);
}
catch { }

that variable i, well, that code is inside a for. THANK YOU SO MUCH!