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); // 鎖定縱橫比
}
浙公網安備 33010602011771號