NPOI 匯入圖片進入Excel
{
double ColWidth = 540.0;
Func<IPicture, (double width, double height)> GetImageDimensions = (pict) =>
{
try
{
return (pict?.GetImageDimension().Width ?? 0, pict?.GetImageDimension().Height ?? 0);
}
catch (Exception ex)
{
return (0, 0);
}
};
byte[] buffer = File.ReadAllBytes(path);
//建立 pic
int picIdx = workbook.AddPicture(buffer, PictureType.PNG);
//建立 畫圖區
var drawing = sheet.CreateDrawingPatriarch();
//確認方位 偏移x1 y1 x2 y2 建立在 colx1 rowy1 colx2 rowy2
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 0, i, 10, i + 1);
//確認位置後建立圖片
var pict = drawing.CreatePicture(anchor, picIdx);
//取得原始長寬 這段要用來縮放圖片
var ImageSize = GetImageDimensions(pict);
//catch error 回0
if (ImageSize.width == 0 || ImageSize.height == 0)
{
_logger.LogInformation(string.Format($"匯出-完工報告 圖片來源 : {0} , 匯入失敗", list));
continue;
}
//依照寬度進行圖片調整 小的拉長 大的縮小
// 取得比例
//依照圖片高度建立Row
row.Height = Convert.ToInt16(ImageSize.height * (ColWidth / ImageSize.width) * 16);
}
留言
張貼留言