利用 System.Windows.Forms.Clipboard 將圖片暫存至剪貼簿,再呼叫 Excel COM 物件的 Paste 方法貼上,是 VB.NET 操作 Excel 插入圖片最直覺的方式。
Imports Microsoft.Office.Interop.Excel
Imports System.Windows.Forms
Dim im As Image = Image.FromFile("C:/picture.bmp") ' 讀取圖檔
Clipboard.SetDataObject(im, True) ' 複製至剪貼簿
Dim xlApp As New Application()
Dim xlBook As Workbook = xlApp.Workbooks.Add()
Dim xlSheet As Worksheet = CType(xlBook.Worksheets("Sheet1"), Worksheet)
' 指定貼上位置 (第 4 列, 第 1 行)
Dim range As Range = xlSheet.Range(xlApp.Cells(4, 1), xlApp.Cells(4, 1))
xlSheet.Paste(range, im) ' 貼上圖片
' 後續可存檔、關閉
xlBook.SaveAs("C:/Output.xlsx")
xlBook.Close()
xlApp.Quit()
' 釋放 COM 物件
Runtime.InteropServices.Marshal.ReleaseComObject(range)
Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet)
Runtime.InteropServices.Marshal.ReleaseComObject(xlBook)
Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)