我想要在 Excel 加载项中包含/嵌入具有预定义布局的 Excel 工作表,但我无法将项目项“工作簿”添加到我的 VSTO 项目,也无法添加对“Excel 工作簿”项目的引用。那么我该怎么做呢?
我的目标是构建一个 Excel 插件,将新工作表添加到现有工作簿(从 SAP 下载)中以聚合数据。
斯文
最佳答案
创建包含工作表的工作簿。如果需要,将工作簿另存为模板。将工作簿作为资源嵌入。如何将资源转换为工作簿/工作表将取决于文档格式。如果使用 SpreadSheet XML (XMLSS),则相当容易。如果是二进制(xls 或 xlt),那么您将必须操作资源。 Excel 无法读取流。
使用 VSTO Excel 加载项项目和项目资源的示例
Public Class ThisAddIn
Private Sub ThisAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
' Start of VSTO generated code
Me.Application = CType(Microsoft.Office.Tools.Excel.ExcelLocale1033Proxy.Wrap(GetType(Excel.Application), Me.Application), Excel.Application)
' End of VSTO generated code
'setup a workbook and worksheet for sample code to work
Dim oWB As Excel.Workbook = Me.Application.Workbooks.Add()
Dim oWS As Excel.Worksheet = CType(oWB.Worksheets.Add, Excel.Worksheet)
'create temporary template
Dim sPath As String = My.Computer.FileSystem.GetTempFileName
My.Computer.FileSystem.WriteAllBytes(sPath, My.Resources.Book1, False)
'open with excel
Dim oTemplate As Excel.Workbook = Me.Application.Workbooks.Add(sPath)
'specify worksheet from a different workbook
' copies the template worksheet into destination workbook
oTemplate.Worksheets.Copy(oWS)
'no longer need template
oTemplate.Close()
'delete the temporary file
My.Computer.FileSystem.DeleteFile(sPath)
'get our worksheet
Dim oReportWS As Excel.Worksheet = CType(oWB.Worksheets.Item("Template"), Excel.Worksheet)
'write our data
CType(oReportWS.Cells(1, 1), Excel.Range).Value2 = "Here I am!"
End Sub
End Class
关于excel - VSTO Excel 2007 : Include or embed a Workbook/Worksheet in an Add-in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2522243/