Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Core
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
InsertPicture("c:/aa.xls", "A2", "c:\aa.jpg", "E:/h.xls")
End Sub
'======author:yansheng==========xls文件插入图片的操作函数InsertPicture==========date:2008/03/17==============
' TempPath: 是xls模板的路径
' RangeName: 是要插入图片的单元格的位置,例如:B4
' 注意: 图片必须是绝对物理路径
' PicturePath: 图片的物理路径
' SaveAsName: 另存为文件的名字和路径,例如:D:/name.xls
'================================================注意===========================================================
'使用该方法必须要导入微软官方提供的office操作的api,步骤如下:右击资源管理器中自己的项目,选择“添加引用...”,
'切换到“com”标签,选择“ Microsoft.Excel.11.0 Object Library”和“ Microsoft.Office.11.0 Object Library”的引用
'类库,单击确定.
'在该方法的页面,导入命名空间:“Imports Microsoft.Office.Interop.Excel”和“Imports Microsoft.Office.Core”
'以上就是准备工作。
'================================================注意===========================================================
Public Function InsertPicture(ByVal TempPath As String, ByVal RangeName As String, ByVal PicturePath As String, ByVal SaveAsName As String) As String
'相当与启动一个execel的应用程序
Dim oExcel As New Microsoft.Office.Interop.Excel.Application
'声明一个共作部
Dim obooks As Microsoft.Office.Interop.Excel.Workbooks
Dim obook As Microsoft.Office.Interop.Excel.Workbook
Dim oSheets As Microsoft.Office.Interop.Excel.Sheets
'声明要对其操作的sheet
Dim oSheet As Microsoft.Office.Interop.Excel.Worksheet
'声明一个单元格类
Dim oRange As Microsoft.Office.Interop.Excel.Range
Dim miss As System.Reflection.Missing
'设置空值
miss = System.Reflection.Missing.Value
'进行Excel的版本检测,该函数是针对Office 2003的操作。
If (oExcel.Version <> "11.0") Then
MsgBox("您的 Excel 版本不是 11.0 (Office 2003),操作可能会出现问题。")
'oExcel.Quit()
Else
'设置启动该excel程序的时候,不显示的打开,在后台运行
oExcel.Visible = False
oExcel.DisplayAlerts = False
obooks = oExcel.Workbooks
'打开模板"TempPath"指定的模板
obook = obooks.Open(TempPath, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss)
oSheets = obook.Worksheets
'得到要操作的execl的sheet
oSheet = CType(oSheets.Item(1), Microsoft.Office.Interop.Excel.Worksheet)
'设置要填充图像的单元格,且得到他的引用
oRange = oSheet.Range(RangeName, miss)
oRange.Select()
Dim PicLeft, PicTop As Int64
PicLeft = Convert.ToSingle(oRange.Left)
PicTop = Convert.ToSingle(oRange.Top)
'在该活动的sheeet的选定单元格里,添加图片,图片的路径是“PicturePath”,100和00是设置图片的大小!
oSheet.Shapes.AddPicture(PicturePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, PicLeft, PicTop, 100, 100)
'把操作后的sheet另存为一个xls文件。
obook.SaveAs(SaveAsName)
obooks.Close()
'释放对象
ReleaseObj(oRange)
ReleaseObj(oSheet)
ReleaseObj(obook)
ReleaseObj(obooks)
ReleaseObj(oExcel)
End If
Return ""
End Function
'释放对象函数
Private Function ReleaseObj(ByRef obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
Catch ex As Exception
Finally
obj = Nothing
End Try
End Function