[筆記][NPOI] 用 NPOI 在 Excel 中插入圖檔

剛好有個需求,需要在 NPOI 產生的 Excel 中,插入一個圖檔,這裡筆記一下,也順便分享給需要的朋友

緣起

剛好有個需求,需要在 NPOI 產生的 Excel 中,插入一個圖檔,這裡筆記一下,也順便分享給需要的朋友

 

相關程式碼

這裡撰寫一個funcion來處理

 


''' <summary>
''' 圖檔放入Excel
''' </summary>
''' <param name="book">XSSFWorkbook</param>
''' <param name="sheet">XSSFSheet</param>
''' <param name="imgPath">圖檔實體位置</param>
''' <remarks></remarks>
Private Sub InertImgtoExcel(ByRef book As XSSFWorkbook, ByRef sheet As XSSFSheet, ByVal imgPath As String)
    Dim bytes As Byte() = System.IO.File.ReadAllBytes(imgPath)
    Dim pictureIdx As Integer = book.AddPicture(bytes, XSSFWorkbook.PICTURE_TYPE_GIF)

    Dim drawing As XSSFDrawing = sheet.CreateDrawingPatriarch()
    Dim helper As XSSFCreationHelper = book.GetCreationHelper
    Dim anchor As XSSFClientAnchor
    '設定圖片位置
    'anchor = helper.CreateClientAnchor()
    anchor = New XSSFClientAnchor(dx1:=5, dy1:=2, dx2:=0, dy2:=0, col1:=0, row1:=0, col2:=0, row2:=0)

    Dim pict As XSSFPicture = drawing.CreatePicture(anchor, pictureIdx)
    pict.Resize()
End Sub

 


以下是簽名:


Microsoft MVP
Visual Studio and Development Technologies
(2005~2019/6) 
topcat
Blog:http://www.dotblogs.com.tw/topcat