Excel 插入圖片設定

Excel插入圖片設定

        public Task<string>  InsertPicToExcel(string path = "圖片檔名.jpg")

{

#region Func 用於調整圖片大小的function 這段在這邊的原因是因為當初寫的地方是API 無法額外寫function

Func<string, (int width, int height)> GetImageDimensions = (path) =>

{

    if (!File.Exists(path))

    {

        Console.WriteLine("找不到圖片");

        return (-1, -1);

    }


    System.Drawing.Image image = System.Drawing.Image.FromFile(path);


    return (image.Width, image.Height);

};

#endregion


 //取得原始長寬

var ImageSize = GetImageDimensions(list);

//長寬比例

double Scale = 1.0;


//依照寬度進行圖片調整 小的拉長 大的縮小

// 當初圖片大小 890 = 23.55cm 

// 因此欄位需求大小為15.5的話 求得值為 = 540

// 取得比例

Scale = 540.0 / ImageSize.width;


//依照圖片高度建立Row

//這邊因為 XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 0, i, 10, i + 1); 這段 因此會自動成為圖片的寬度

//簡單來講 把任意圖片拉為 540 x (Y * 540 / ImageSize.width) 大小

row.Height = Convert.ToInt16(ImageSize.height * Scale * 16);


//讀取為byte後寫入為 png

byte[] buffer = File.ReadAllBytes(list);

int picIdx = workbook.AddPicture(buffer, PictureType.PNG);


var drawing = sheet.CreateDrawingPatriarch();

//指定插入位置以及偏移量

//前四個為在起始格子的偏移量 後四個分別為起始欄位坐標(左上) 以及結束座標(左上)

XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 0, i, 10, i + 1);

//建立圖片

var pict = drawing.CreatePicture(anchor, picIdx);

}

參考:

ChatGpt

https://blog.csdn.net/weixin_38138153/article/details/116173454

留言

這個網誌中的熱門文章

無法載入檔案或組件 'System.IO.Compression' 或其相依性的其中之一。

MongoDB 入門

javascript 更改屬性及創建標籤