当我从docx文件的路径中打开WordProcessingDocument时,会创建功能区。但是,当我从docx文件的字节内容中打开相同内容时,它不会被创建。以下内容未显示docx文件中的功能区: -
public void AddRibbonToTemplate(byte[] templateContent)
{
string sanitizedRibbonXml = GetRibbonXML().ToString().Replace("xmlns=\"\"", "");
MemoryStream stream = new MemoryStream();
stream.Write(templateContent, 0, templateContent.Length);
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(stream, true))
{
MainDocumentPart mainPart = myDoc.MainDocumentPart;
if (myDoc.GetPartsCountOfType<RibbonExtensibilityPart>() > 0)
myDoc.DeletePart(myDoc.GetPartsOfType<RibbonExtensibilityPart>().First());
RibbonExtensibilityPart ribbonExtensibilityPart = myDoc.AddNewPart<RibbonExtensibilityPart>();
ribbonExtensibilityPart.CustomUI = new DocumentFormat.OpenXml.Office.CustomUI.CustomUI(sanitizedRibbonXml);
myDoc.CreateRelationshipToPart(ribbonExtensibilityPart);
}
stream.Close();
}
下面显示了功能区: -
public void AddRibbonToTemplate(string documentFileName)
{
string sanitizedRibbonXml = GetRibbonXML().ToString().Replace("xmlns=\"\"", "");
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(documentFileName, true))
{
MainDocumentPart mainPart = myDoc.MainDocumentPart;
if (myDoc.GetPartsCountOfType<RibbonExtensibilityPart>() > 0)
myDoc.DeletePart(myDoc.GetPartsOfType<RibbonExtensibilityPart>().First());
RibbonExtensibilityPart ribbonExtensibilityPart = myDoc.AddNewPart<RibbonExtensibilityPart>();
ribbonExtensibilityPart.CustomUI = new DocumentFormat.OpenXml.Office.CustomUI.CustomUI(sanitizedRibbonXml);
myDoc.CreateRelationshipToPart(ribbonExtensibilityPart);
}
}
GetRibbonXml()获取功能区的XML。我正在移除xmlns =“”,它将被添加到功能区元素中(来自问题here)。
有人可能会想到为什么没有添加功能区。即使是customUI文件夹也没有添加到单词zip文件中。可以帮助。
答案 0 :(得分:0)
我应该通过将流写入文件来验证流。以下是代码: -
public void AddRibbonToTemplate(byte[] templateContent)
{
string sanitizedRibbonXml = GetRibbonXML().ToString().Replace("xmlns=\"\"", "");
using (MemoryStream stream = new MemoryStream())
{
stream.Write(templateContent, 0, (int)templateContent.Length);
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(stream, true))
{
MainDocumentPart mainPart = myDoc.MainDocumentPart;
if (myDoc.GetPartsCountOfType<RibbonExtensibilityPart>() > 0)
myDoc.DeletePart(myDoc.GetPartsOfType<RibbonExtensibilityPart>().First());
RibbonExtensibilityPart ribbonExtensibilityPart = myDoc.AddNewPart<RibbonExtensibilityPart>();
ribbonExtensibilityPart.CustomUI = new DocumentFormat.OpenXml.Office.CustomUI.CustomUI(sanitizedRibbonXml);
myDoc.CreateRelationshipToPart(ribbonExtensibilityPart);
}
using (FileStream fileStream = new FileStream("Test20.docx",
System.IO.FileMode.CreateNew))
{
stream.WriteTo(fileStream);
}
}
}