Search code examples
c#excelnpoi

Place an image and let it align right in a merged cell using NPOI


As title. My goal is to put a company logo on my excel so it can be shown at the lower-right corner of a paper. Assume that the CompanyImageRawData stores the byte array of the company logo, and _IWorkbook is my excel body.

private void Cert_PageLowerCompanyImageDeploy(ref IRow LowerRow,int ColL=0,int ColR = 3)
        {
            int iCompanyImageIndex = _IWorkbook.AddPicture(CompanyImageRawData, PictureType.PNG);
            LowerRow.Height = 1800;
            LowerRow.Sheet.AddMergedRegion(new CellRangeAddress(LowerRow.RowNum, LowerRow.RowNum, 0, ColR));
            ICell ClImageArea = LowerRow.CreateCell(0);
            ClImageArea.CellStyle = new ExcelCellStyle
            {
                TextAlignLR = HorizontalAlignment.Center
            }.CreateCellstyle(ref _IWorkbook);
            ICreationHelper helper = _IWorkbook.GetCreationHelper();
            IDrawing drawing = LowerRow.Sheet.CreateDrawingPatriarch();
            IClientAnchor anchor = helper.CreateClientAnchor();
            anchor.AnchorType = AnchorType.MoveAndResize;
            anchor.Col1 = ColL;//0 index based column
            anchor.Col2 = ColR;
            anchor.Row1 = LowerRow.RowNum;//0 index based row
            anchor.Row2 = LowerRow.RowNum;
            IPicture picture = drawing.CreatePicture(anchor, iCompanyImageIndex);
            picture.Resize(0.7, 1);
            anchor.Dx2 = 0;
        }

But my comapny logo is shown at the lower-left corner in my excel not at lower-right. Could someone guide me to fix it?


Solution

  • Setting Col1 & Col2 properties to ColR should fix it

     anchor.Col1 = ColR;
     anchor.Col2 = ColR;