NPOI Excel指定范围内插入图片(纵横比),考虑列宽,行高比。
// I assume you want to insert the image into the worksheet loaded in the workbook parameter
// You can adjust the ratio variable accordingly to control the ratio of width and height
// You can also adjust maxWidth and maxHeight to set the maximum size of the image on the worksheet
internal static void InsertImageWithRatio(IWorkbook workbook, int sheetIndex, int firstColumn, int firstRow, int lastColumn, int lastRow, string imagePath)
{
ISheet sheet = workbook.GetSheetAt(sheetIndex);
var width = 0.0;
// 获取列宽度的像素大小
for (int column = firstColumn; column < lastColumn; column++)
{
width += Math.Round(sheet.GetColumnWidthInPixels(column) * 1.285, 0);
//Console.WriteLine($"Column {column} width in pixels: {width}");
}
var height = 0.0;
// 获取行高度的像素大小
var heightInPoints = sheet.GetRow(firstRow)?.HeightInPoints ?? sheet.DefaultRowHeightInPoints;
for (int row = firstRow; row < lastRow; row++)
{
height += Math.Round(heightInPoints * 1.666f, 0);
//Console.WriteLine($"Row {row} height in pixels: {height}");
}
var drawing = sheet.CreateDrawingPatriarch();
// 图片位置和大小
var anchor = drawing.CreateAnchor(0, 0, 0, 0, firstColumn, firstRow, lastColumn, lastRow);
anchor.AnchorType = AnchorType.MoveDontResize;
FileStream file = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[file.Length];
file.Read(buffer, 0, (int)file.Length);
Image image = Image.Load(buffer);
int imageWidth = image.Width;
int imageHeight = image.Height;
var pictureIndex = workbook.AddPicture(buffer, PictureType.PNG);
var picture = drawing.CreatePicture(anchor, pictureIndex);
// 根据图片的宽高比例进行等比例缩放
float widthRatio = imageWidth / (float)width;
float heightRatio = imageHeight / (float)height;
float scaleRatio = Math.Min(widthRatio, heightRatio);
// 根据图片的宽高比例进行等比例缩放
float colWidth = (float)width / imageWidth * scaleRatio;
float rowHeight = (float)height / imageHeight * scaleRatio;
picture.Resize(rowHeight, colWidth); // 锁定纵横比
}