我有以下代码WordprocessingDocument
。我可以使用 OpenXMl 编辑文档,然后删除然后添加带有更新的公司信息的页眉和页脚。
using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(filestream, true))
{
// Get the main document part
MainDocumentPart mainDocumentPart = wdDoc.MainDocumentPart;
// Delete the existing header and footer parts
mainDocumentPart.DeleteParts(mainDocumentPart.HeaderParts);
mainDocumentPart.DeleteParts(mainDocumentPart.FooterParts);
// Create a new header part
HeaderPart headerPart = mainDocumentPart.AddNewPart<HeaderPart>();
headerPart.Header = header;
// Create header content
// Code not included
// Create a new footer part
FooterPart footerPart = mainDocumentPart.AddNewPart<FooterPart>();
// Create footer content
// Code not included
foreach (var section in sections)
{
// Delete existing references to headers and footers
section.RemoveAllChildren<HeaderReference>();
section.RemoveAllChildren<FooterReference>();
// Create the new header and footer reference node
section.PrependChild<HeaderReference>(new HeaderReference() { Id = headerPartId });
section.PrependChild<FooterReference>(new FooterReference() { Id = footerPartId });
PageMargin pageMargin = new PageMargin()
{
Top = 0,
Right = (UInt32Value)504U,
Bottom = 504,
Left = (UInt32Value)504U,
Header = (UInt32Value)360U,
Footer = (UInt32Value)360U,
Gutter = (UInt32Value)0U
};
section.Append(pageMargin);
}
mainDocumentPart.Document.Save();
wdDoc.Close();
}
我正在尝试为 做同样的事情SpreadsheetDocument
,但我不知道如何删除/删除现有的页眉和页脚。我认为DeletePart
as 的一部分OpenXmlPartContainer
which 是OpenXmlPart : OpenXmlPartContainer
. 电子表格有页眉和页脚,但我不知道如何访问它们。
using (SpreadsheetDocument workbook = SpreadsheetDocument.Open(filestream, true))
{
// Get the spreadsheet document parts
WorkbookPart wbPart = workbook.WorkbookPart;
WorksheetPart wsPart = wbPart.WorksheetParts.First();
// Delete existing header
Header header = wsPart.Worksheet.Descendants<Header>().FirstOrDefault();
if (header != null)
{
wsPart.DeleteParts<Header>(header);
}
// Delete existing footer
Footer footer = wsPart.Worksheet.Descendants<Footer>().FirstOrDefault();
if (footer != null)
{
wsPart.DeleteParts<Footer>(footer);
}
}