最近使用 EPPlus 來解決 , Excel 問題,不免俗的又是遇到一個萬年的問題
如何插入圖片,其實在 Excel 中插入圖片一直都是一個麻煩的問題,因為圖片其實都是浮在儲存格的上面
所以,基本上你很難控制儲存格的大小,但是其實是有一個小技巧,以前我在處理 Excel 也是這樣處理的..
這時候就不能夠用上一篇文章寫得輕鬆倒入資料,這時候要數格子了
其中有幾個處理的技巧
1. 插入圖片位置,需要 Row-1, Column-1 ,因為對齊的關係,才會對應到你要的位置
2.插入圖片的時候 其實為了使用 AutoFit 我將該儲存格放入一個 UTF 的一個空白字元,並且我將該儲存格FontSize 設定成 200px
這時候,只要下 AutoFit 就會變得跟圖片一樣寬了,這是小技巧
其中我用的空白字是 https://www.compart.com/en/unicode/U+2002
不能用一般半形或是全形的空白,都是沒用的
3. 插入圖片的 Name 一定要是 Unique 不然會出現
Unhandled exception. System.Exception: Name already exists in the drawings collection at
OfficeOpenXml.Drawing.ExcelDrawings.ValidatePictureFile(String Name, FileInfo ImageFile)
廢話不多說就給 Code 吧,因為要簡單的數格子,該說的重點都在上面跟 Code 裡面了
//Data for Test
var staffs = new List
{
new Staff{ Id = "S1", Name="DONMA", Mobile="0912456789", Salary=999_999m, Create = new DateTime(1950, 3, 15) },
new Staff{Id = "S2", Name="JOHN", Mobile="0922456789", Salary=199_999m, Create = new DateTime(1962, 6, 10)},
new Staff{ Id = "S3", Name="DELTA", Mobile="0912456799", Salary=299_999m, Create = new DateTime(1971, 10, 2)}
};
using (var package = new ExcelPackage(AppDomain.CurrentDomain.BaseDirectory + "samplejpg.xlsx"))
{
// using the Actor class above
var sheet = package.Workbook.Worksheets.Add("Sheet1");
sheet.Cells["A1"].Value = "員工編號";
sheet.Cells["B1"].Value = "姓名";
sheet.Cells["C1"].Value = "到值日";
sheet.Cells["D1"].Value = "電話";
sheet.Cells["E1"].Value = "薪水";
sheet.Cells["F1"].Value = "照片";
//測試在圖片之後是不是可以正常顯示
sheet.Cells["G1"].Value = "TEST2";
var row = 2;
foreach (var staff in staffs)
{
sheet.Cells[row, 1].Value = staff.Id;
sheet.Cells[row, 2].Value = staff.Name;
sheet.Cells[row, 3].Value = staff.Create.ToString("yyyy-MM-dd");
sheet.Cells[row, 4].Value = staff.Mobile;
sheet.Cells[row, 5].Value = staff.Salary;
//插入圖片
//Name 一定要 unique
var pic = sheet.Drawings.AddPicture(staff.Id + "_IMG", AppDomain.CurrentDomain.BaseDirectory + "sample1.jpg");
pic.SetPosition(row - 1, 25, 5, 25);
pic.SetSize(200, 200);
sheet.Row(row).Height = 200;
//故意插入一個看似空白的字元
//並且設定圖片的寬度
sheet.Cells[row, 6].Value = " ";
sheet.Cells[row, 6].Style.Font.Size = 200;
//test after image column.
sheet.Cells[row, 7].Value = staff.Id;
row++;
}
//之後就可以舒服的直接使用 AutoFit 不用在那算指定寬度
sheet.Columns.AutoFit();
package.Save();
}
其實每張圖片後面都藏有一個空白的 U+2002 只看不到而已,把圖片移開會看到後面有一個空白
