使用包装将宏文件添加到XLSX/XLSM文件中



我正在使用System.IO.Packaging来构建简单的Excel文件。我们的一位客户想拥有一个自动宏来更新数据并重新校准表。

拉开现有床单,我可以看到,您需要做的就是添加vbaProject.bin文件并在_rels中更改一些类型。因此,我在一个文件中制作了宏,提取了vbaProject.bin,将其复制到另一个文件中,然后有宏。

我知道如何以XML格式(例如床单或工作簿本身(添加包装零件,但是我从未添加二进制文件,我无法弄清楚。有人做过吗?

好吧,我明白了。遵循TNTINMN的建议:

  1. 打开一个新的工作簿并输入宏。将扩展名更改为zip,打开它,打开xl文件夹并复制vbaProject.bin到容易找到的地方。

  2. 在您的.NET代码中,制作新部分并将其添加到包装中'xl/vbaproject.bin'。从字节上复制字节 您提取的vbaProject.bin。它将被压缩添加字节。

  3. 然后,您必须在工作簿中添加一个关系,以指向您的新文件。您可以在 xl/_rels/workbook.xml.rels

  4. 您还必须在文档,进入[Content Types].xls。当您使用CreatePart的ContentType参数

  5. 时,这会自动发生。
  6. 最后,将扩展名更改为.xlsm或.xltm

我正在从代码中的许多地方提取以下内容,所以这是伪...

'the package...
Dim xlPackage As Package = Package.Open(WBStream, FileMode.Create)
'start with the workbook, we need the object before we physically insert it
Dim xlPartUri As URI = PackUriHelper.CreatePartUri(New Uri(GetAbsoluteTargetUri("/", "xl/workbook.xml"), UriKind.Relative)) 'the URI is relative to the outermost part of the package, /
Dim xlPart As PackagePart = xlPackage.CreatePart(xlPartUri, "application/vnd.ms-excel.sheet.macroEnabled.main+xml", CompressionOption.Normal)
'add an entry in the root _rels folder pointing to the workbook
xlPackage.CreateRelationship(xlPartUri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "xlWorkbook") 'it turns out the ID can be anything unique
'now that we have the WB part, we can make our macro relative to it
Dim xlMacroUri As URI = PackUriHelper.CreatePartUri(New Uri(GetAbsoluteTargetUri("/xl/workbook.xml", "vbaProject.bin"), UriKind.Relative))
Dim xlMacroPart as PackagePart = xlPackage.CreatePart(xlPartUri, "application/vnd.ms-office.vbaProject", CompressionOption.Normal)
'time we link the vba to the workbook
xlParentPart.CreateRelationship(xlPartUri, TargetMode.Internal, "http://schemas.microsoft.com/office/2006/relationships/vbaProject", "rIdMacro") 'the ID on the macro can be anything as well
'copy over the data from the macro file
Using MacroStream As New FileStream("C:yourdirectoryvbaProject.bin", FileMode.Open, FileAccess.Read)
    MacroStream.CopyTo(xlMacroPart.GetStream())
End Using
'
'now write data into the main workbook any way you like, likely using new Parts to add Sheets

相关内容

  • 没有找到相关文章

最新更新