开发环境基于VSTO:visual studio 2010,VB .Net,excel 2007,文档级别的定制程序。
需求是在sheet的左侧停靠System.Windows.Forms.TreeView控件,实现类似资源浏览器的效果,另外,tree节点使用自定义的图标,支持复选框。
首先准备好树节点的图标,使用visual studio 2010自带的图标可以省去很多麻烦(在安装目录\Common7\VS2010ImageLibrary)。我挑选了4个16x16大小的图标拷贝到vsto工程下的Resources目录下。通过Project->xxx Properties->Resources->AddResource->Add Existing File添加图标到工程中,代码中就可以用My.Resources.aaa的方式引用了(aaa为图标名称)。
接下来,在sheet初始化函数中完成图标与TreeView控件的初始化代码,如果TreeView控件的内容需要随sheet数据变化而刷新,还需要在sheet_change函数中添加代码。
Public Class Sheet1
Public WithEvents m_tree As New TreeView
Public m_imageList As New ImageList
Private Sub Sheet1_Startup() Handles Me.Startup
m_imageList.ColorDepth = ColorDepth.Depth32Bit
‘第一个参数为ImageKey,类似Image名称的作用
m_imageList.Images.Add("cfg", My.Resources.book_notebook)
m_imageList.Images.Add("algo", My.Resources._075b_UpFolder_16x16_72)
m_imageList.Images.Add("scen", My.Resources.PlayHS)
m_imageList.Images.Add("warning", My.Resources._109_AllAnnotations_Warning_16x16_72)
Globals.ThisWorkbook.ActionsPane.Controls.Add(m_tree)
Application.CommandBars("Task Pane").Position = Microsoft.Office.Core.MsoBarPosition.msoBarLeft
m_tree.ImageList = m_imageList
m_tree.CheckBoxes = True
‘tree的dock自动调整大小,需要在add到pane后再设置,否则不会生效
m_tree.Dock = DockStyle.Fill
With m_tree
.BeginUpdate()
.Nodes.Clear()
.Nodes.Add(New TreeNode(Me.Name))
.Nodes(0).ImageKey = "cfg"
.Nodes(0).SelectedImageKey = "cfg"
Dim idx As Integer = .Nodes.Add(New TreeNode("Node1"))
.Nodes(idx).ImageKey = "algo"
.Nodes(idx).SelectedImageKey = "algo"
Dim idx2 As Integer = .Nodes(idx).Nodes.Add(New TreeNode("case1_5M"))
.Nodes(idx).Nodes(idx2).ImageKey = "scen"
.Nodes(idx).Nodes(idx2).SelectedImageKey = "scen"
.EndUpdate()
End With
End Sub
Private Sub Sheet1_Change(Target As Microsoft.Office.Interop.Excel.Range) Handles Me.Change
‘do Tree Refresh
End Sub
End Class
效果图: