如何在C#中移除Word文档页眉页脚并修改字体后保存?
Great work on getting the font modification up and running! Let's expand your code to include removing headers and footers, plus add proper cleanup to avoid leaving Word processes lingering in the background.
Here's the complete modified code:
using Word = Microsoft.Office.Interop.Word; using System.Runtime.InteropServices; // For clean COM object release class WordDocumentTool { static void Main() { Word.Application wordApp = null; Word.Document targetDoc = null; try { wordApp = new Word.Application(); // Replace with your actual document path targetDoc = wordApp.Documents.Open(@"C:\Your\File\Path\Document.docx"); // Modify font for the entire document Word.Range fullDocumentRange = targetDoc.Content; fullDocumentRange.Font.Name = "Times New Roman"; // Remove headers and footers from all document sections foreach (Word.Section section in targetDoc.Sections) { // Clear all headers in the section foreach (Word.HeaderFooter header in section.Headers) { if (header.Exists) { // Unlink from previous sections to ensure we modify this header header.LinkToPrevious = false; // Delete the header content header.Range.Delete(); } } // Clear all footers in the section foreach (Word.HeaderFooter footer in section.Footers) { if (footer.Exists) { footer.LinkToPrevious = false; footer.Range.Delete(); } } } // Save the updated document targetDoc.Save(); } catch (Exception ex) { Console.WriteLine($"Oops, something went wrong: {ex.Message}"); } finally { // Clean up to prevent orphaned Word processes if (targetDoc != null) { targetDoc.Close(); Marshal.ReleaseComObject(targetDoc); } if (wordApp != null) { wordApp.Quit(); Marshal.ReleaseComObject(wordApp); } } } }
Key Additions Explained:
- Header/Footer Removal: We loop through every section in the document (since Word files can have multiple sections with unique headers/footers). For each header/footer, we first unlink it from previous sections (so changes apply to this section specifically), then delete its content.
- Cleaner Font Modification: Replaced the
start/endobject approach withtargetDoc.Content—it does the same job of targeting the entire document but is more concise. - Proper Cleanup: Wrapped the code in a try-finally block to ensure we always close the document and quit the Word app, even if an error occurs. Using
Marshal.ReleaseComObjecthelps avoid hidden Word processes running in the background, which is a common pitfall with interop code.
Quick Notes:
- Swap out the file path in
Documents.Open()with your actual document location. - If your document only has one section, you could skip the loop and target
targetDoc.Sections[1]directly, but looping ensures no headers/footers are missed across all sections. - Make sure you have the
Microsoft.Office.Interop.WordNuGet package installed in your project.
内容的提问来源于stack exchange,提问作者nani gadde
相关产品推荐
相关产品推荐

