Search code examples
c#excelnpoi

Add image to Excel (.xlsx) using NPOI C#


I want to insert image to an XLSX file (not xls) using NPOI. I am using XSSFWorkbook and XSSFSheet

byte[] data = File.ReadAllBytes("SomeImage.jpg");
int picInd = workbook.AddPicture(data, XSSFWorkbook.PICTURE_TYPE_JPEG);
XSSFCreationHelper helper = workbook.GetCreationHelper() as XSSFCreationHelper;
XSSFDrawing drawing = _sheet.CreateDrawingPatriarch() as XSSFDrawing;
XSSFClientAnchor anchor = helper.CreateClientAnchor() as XSSFClientAnchor;
anchor.Col1 = 1;
anchor.Row1 = 1;
XSSFPicture pict = drawing.CreatePicture(anchor, picInd) as XSSFPicture;

The file is saved successfully. but while opening it showing the following error and on clicking yes, it does not display the image. enter image description here


Solution

  • I got the solution:

    byte[] data = File.ReadAllBytes("someImage.png");
    int pictureIndex = workbook.AddPicture(data, PictureType.PNG);
    ICreationHelper helper = workbook.GetCreationHelper();
    IDrawing drawing = _sheet.CreateDrawingPatriarch();
    IClientAnchor anchor = helper.CreateClientAnchor();
    anchor.Col1 = 0;//0 index based column
    anchor.Row1 = 0;//0 index based row
    IPicture picture = drawing.CreatePicture(anchor, pictureIndex);
    picture.Resize();