You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修正NPOI代码,使公司Logo显示在合并单元格右下角?

修正NPOI中Excel合并单元格内Logo右对齐至纸张右下角的代码

问题分析

当前代码的核心问题是仅指定了图片的列范围,但未通过锚点偏移量控制图片在合并单元格内的水平对齐位置,导致图片默认靠左显示。另外,单元格样式的文本对齐对图片位置无影响,图片位置完全由IClientAnchor参数决定。

关键修改点

  • 调整IClientAnchor的水平偏移参数(Dx1、Dx2),将图片定位到合并单元格的右边缘
  • 修正锚点的列绑定逻辑,确保图片锚定在合并区域的右侧列
  • 设置工作表的打印页边距,保证打印时图片正好落在纸张右下角

修正后的代码

private void Cert_PageLowerCompanyImageDeploy(ref IRow LowerRow, int ColL = 0, int ColR = 3)
{
    int iCompanyImageIndex = _IWorkbook.AddPicture(CompanyImageRawData, PictureType.PNG);
    LowerRow.Height = 1800;
    var sheet = LowerRow.Sheet;
    
    // 合并目标单元格
    sheet.AddMergedRegion(new CellRangeAddress(LowerRow.RowNum, LowerRow.RowNum, ColL, ColR));
    
    // 设置打印页边距(单位:英寸,确保图片落在纸张右下角区域)
    sheet.SetMargin(MarginType.Top, 0.75);
    sheet.SetMargin(MarginType.Bottom, 0.75);
    sheet.SetMargin(MarginType.Left, 0.75);
    sheet.SetMargin(MarginType.Right, 0.75);
    
    ICreationHelper helper = _IWorkbook.GetCreationHelper();
    IDrawing drawing = sheet.CreateDrawingPatriarch();
    IClientAnchor anchor = helper.CreateClientAnchor();
    
    // 锚点设置:随单元格移动并支持调整大小
    anchor.AnchorType = AnchorType.MoveAndResize;
    
    // 将图片锚定到合并区域的右侧列
    anchor.Col1 = ColR;
    anchor.Col2 = ColR;
    anchor.Row1 = LowerRow.RowNum;
    anchor.Row2 = LowerRow.RowNum;
    
    // 计算图片的EMU单位尺寸(1像素≈9525 EMU)
    var pictureData = _IWorkbook.GetAllPictures()[iCompanyImageIndex];
    double scaleWidth = 0.7;
    double scaleHeight = 1.0;
    int targetWidthEMU = (int)(pictureData.Width * scaleWidth * 9525);
    int targetHeightEMU = (int)(pictureData.Height * scaleHeight * 9525);
    
    // 设置水平偏移:让图片左边缘对齐到单元格右边缘减去图片宽度的位置,实现右对齐
    int colWidthEMU = (int)(sheet.GetColumnWidthInPixels(ColR) * 9525);
    anchor.Dx1 = colWidthEMU - targetWidthEMU;
    anchor.Dx2 = colWidthEMU;
    
    // 设置垂直偏移:让图片垂直居中于当前行
    int rowHeightEMU = (int)(LowerRow.HeightInPoints * 9525 * 0.75);
    anchor.Dy1 = (rowHeightEMU - targetHeightEMU) / 2;
    anchor.Dy2 = anchor.Dy1 + targetHeightEMU;
    
    // 创建图片对象
    IPicture picture = drawing.CreatePicture(anchor, iCompanyImageIndex);
}

补充说明

  1. EMU单位规则:NPOI使用EMU作为偏移量单位,1像素≈9525 EMU,计算时需保持单位统一
  2. 页边距调整:可根据实际纸张规格修改SetMargin的参数值,确保图片打印位置符合需求
  3. 垂直位置调整:修改Dy1参数可调整图片在单元格内的垂直位置,比如设置为0可让图片靠上对齐

内容的提问来源于stack exchange,提问作者Gary Lu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 08:47:37