这个写入的图片不会自动缩放

BUG反馈 · 27 次浏览
zdf153 创建于 9天23小时前
//.cs 文件类型,便于外部编辑时使用
using System.Windows.Forms;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
using System.Drawing;

public static class QuickerScript
{
    // Quicker将会调用的函数
    public static void Exec(Quicker.Public.IStepContext context)
    {
        var workbook = (IWorkbook)context.GetVarValue("workbook");
        var sheet = (ISheet)context.GetVarValue("sheet");
        var bmp = (Image)context.GetVarValue("image");
        int row = Convert.ToInt32(context.GetVarValue("row"));
        int col = Convert.ToInt32(context.GetVarValue("col"));

        // 将图片转换为 byte 数组
        byte[] bytes = ImageToByteArray(bmp);
        int pictureIdx = workbook.AddPicture(bytes, PictureType.PNG);

        // 创建绘图对象
        IDrawing drawing = sheet.CreateDrawingPatriarch();
        ICreationHelper helper = workbook.GetCreationHelper();
        IClientAnchor anchor = helper.CreateClientAnchor();

        // 设置锚点位置(图片起始位置)
        anchor.Col1 = col;
        anchor.Row1 = row;
        anchor.Col2 = col + 1;
        anchor.Row2 = row + 1;

        // 设置锚点像素偏移,填满单元格
        anchor.Dx1 = 0;
        anchor.Dy1 = 0;
        anchor.Dx2 = 1023; // 最大列偏移,填满
        anchor.Dy2 = 255;  // 最大行偏移,填满
        anchor.AnchorType = AnchorType.MoveAndResize;

        // 插入图片
        IPicture picture = drawing.CreatePicture(anchor, pictureIdx);
    }

    // 将 Image 转换为 PNG 格式的 byte[]
    public static byte[] ImageToByteArray(Image imageIn)
    {
        using (var ms = new MemoryStream())
        {
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            return ms.ToArray();
        }
    }

    // 可选:用于获取列宽像素(用于扩展场景)
    public static float GetColumnWidthInPixels(ISheet sheet, int columnIndex)
    {
        int cw = sheet.GetColumnWidth(columnIndex); // 1/256字符单位
        return cw / 256f * 7f; // 粗略估算为每字符约7px
    }
}

ai写的可以填满单元格

zdf153 最后更新于 2025/5/14

回复内容
CL 9天18小时前
#1

感谢分享~

回复主贴