是否可以使用Word API将现有Word文档的宏复制到新创建的Word文档中?
我试过C#。我知道必须更改Word中的信任级别才能这样做。我也能够确定文档中有宏。
但是,如果我使用C#创建一个新文档,它没有VBProject并且是只读的。
以下是一些代码,用于解释我尝试做的事情:
Word.Document oldDoc = word.Documents.Open(oldFilePath);
if (!oldDoc.HasVBProject)
return;
Word.Document newDoc = word.Documents.Add();
FileInfo file = new FileInfo(filePath);
foreach (var component in oldDoc.VBProject.VBComponents)
{
newDoc.VBProject.VBComponents.Add(component);
}
答案 0 :(得分:0)
OpenXML似乎可以用于此目的,请参阅MSDN
中的示例代码using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Packaging;
namespace CtrlInsertMacro
{
class Program
{
static void Main(string[] args)
{
using (WordprocessingDocument destDoc = WordprocessingDocument.Create("destination.docm", WordprocessingDocumentType.MacroEnabledDocument))
{
WordprocessingDocument srcDoc = WordprocessingDocument.Open("macrosource.docm", false);
MainDocumentPart mainPart = destDoc.AddMainDocumentPart();
// Create the document structure and add some text.
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text("This is a copied macro enabled doc. Hit Ctrl+Insert Now."));
// Get VBA parts from source document
VbaProjectPart vbaSrc = srcDoc.MainDocumentPart.VbaProjectPart;
VbaDataPart vbaDatSrc = vbaSrc.VbaDataPart;
CustomizationPart keymapSrc = srcDoc.MainDocumentPart.CustomizationPart;
// Create VBA parts in destination document
VbaProjectPart vbaProjectPart1 = mainPart.AddNewPart<VbaProjectPart>("rId9");
VbaDataPart vbaDataPart1 = vbaProjectPart1.AddNewPart<VbaDataPart>("rId1");
CustomizationPart customKeyMapPart = mainPart.AddNewPart<CustomizationPart>("rId10");
// Copy part contents
vbaProjectPart1.FeedData(vbaSrc.GetStream());
vbaDataPart1.FeedData(vbaDatSrc.GetStream());
customKeyMapPart.FeedData(keymapSrc.GetStream());
}
}
}
}