Reputation: 1805
I have a word document that has multiple sections, and I need to create multiple documents based on each section.
I have tried below but unable to add a section in new document.
Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document document = appWord.Documents.Open("file.docx");
foreach (Microsoft.Office.Interop.Word.Section sec in document.Sections)
{
Microsoft.Office.Interop.Word.Document documentNew = new Microsoft.Office.Interop.Word.Document();
documentNew.Sections.Add(sec.Range);
documentNew.SaveAs2("new.docx");
}
Upvotes: 0
Views: 1271
Reputation: 9479
From what I can decipher, you have a Word document with “sections.” You want to open that document, loop through all the “sections” in it AND for each “section” found in the document, you want to create a “new” Word document such that the first section in the new doc is the same as the current section in the original document. I hope I got that right.
Looking at your current posted code… The foreach
loops through each section of the original document. Then a new Word doc is created, and a new “section” is added to the new document with…
documentNew.Sections.Add(sec.Range);
This line is going to throw an exception for numerous reasons. However, it should be clear “why” this may not work. In the code above, we are trying to “ADD” a new section to the new document. The problem is that “what” we are trying to add … sec.Range
… BELONGS to the original document and a clear “reference” problem is created as you will have “one” section in “both” documents. It would appear clear that this alone may cause problems, however, a copy-paste may be a solution.
Using a copy-paste will at least remedy the dual reference problem described above. The code below uses the “Word/Interop copy-paste” to copy the “section” from the original document into a new document. Since we can not really “copy” the “section” object and “add” it to the new document, another approach is to simply “copy” the “sections” Range
from the original document, then add a new “section” to the new document, then finally “paste” the Range
into the new section. I hope that makes sense.
Next, the current code is overwriting “new.docx” file with each section, so you only end up with one file that will contain the last section from the original document. If we want a “new” Word document for each section, then we will need some kind of file name incrementor to prevent the files getting overwritten.
And finally, a word of caution when using interop or other com objects. It is important to “close/release” the com objects your code creates. Specifically, in this case, the appWord
object and the document
object. In your current code, since I am confident it will throw an exception, if you run it numerous times again and again… then… go look in your task manager… I am confident you will see numerous Word apps running in background. This is referred to as a leaking resource and you want to avoid this.
Usually when dealing with interop, be it Word or Excel etc… I have found the easiest solution is to “wrap” all the code that interacts with the Office objects inside a “Try/Catch/Finally” statement. All the code goes in the “try” section, a “catch” section to display the error when one appears, and the most important “finally” section where we can properly close and release the com objects. This will help properly close the Word app even if an exception is thrown. I highly recommend using a try/catch/finally anytime you use interop.
The method below SaveSectionsToFiles(string sourceFile, string destPath)
… demonstrates what is described above.
private void SaveSectionsToFiles(string sourceFile, string destPath) {
string curFileName;
int curFileNumber = 1;
Word.Application appWord = null;
Word.Document sourceDoc = null;
Word.Document destDoc = null;
Word.Section tempSection;
try {
appWord = new Word.Application();
//appWord.Visible = true;
sourceDoc = appWord.Documents.Open(sourceFile);
foreach (Word.Section sec in sourceDoc.Sections) {
sec.Range.Copy(); // <- Copy section range from original doc
destDoc = new Word.Document();
destDoc.Sections.Add();
tempSection = destDoc.Sections[1];
tempSection.Range.Paste(); // <- Paste range into new section of new document
curFileName = destPath + "NewDocSec_" + curFileNumber++ + ".docx";
destDoc.SaveAs2(curFileName);
destDoc.Close();
}
}
catch (Exception ex) {
MessageBox.Show("Error: " + ex.Message);
}
finally {
if (sourceDoc != null) {
sourceDoc.Close();
Marshal.ReleaseComObject(sourceDoc);
}
if (appWord != null) {
appWord.Quit();
Marshal.ReleaseComObject(appWord);
}
}
}
Usage….
private void button1_Click(object sender, EventArgs e) {
string sourceFile = @"D:\Test\WordTests\SectionDocument.docx";
string destPath = @"D:\Test\WordTests\";
SaveSectionsToFiles(sourceFile, destPath);
}
Upvotes: 2