Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- using Word = Microsoft.Office.Interop.Word;
- using System.IO;
- namespace WordTest
- {
- class Program
- {
- public static void Main(string[] args)
- {
- object oMissing = System.Reflection.Missing.Value;
- // Start Word and create a new document.
- Word.Application oWord;
- Word.Document oDocOriginal; // the template
- Word.Document oDocNew; // the output
- object oEndOfDoc = @"\endofdoc"; // predefined bookmark of document end
- oWord = null;
- try
- {
- oWord = new Word.Application();
- oWord.Visible = false;
- // We are reading th template
- object oFileName = Path.GetFullPath(@"..\..\Dyplom.doc");
- oDocOriginal = oWord.Documents.Add(ref oFileName, ref oMissing, ref oMissing, ref oMissing);
- // We are creating the output document
- oDocNew = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
- string[] students = new string[] { "Jan Kowalski", "Paweł Nowak", "Anna Nowakowska" };
- // for each student
- for (int i = 0; i < students.Length; i++)
- {
- // We're copying data from the template document
- oDocNew.Bookmarks.get_Item(ref oEndOfDoc).Range.FormattedText = oDocOriginal.Content.FormattedText;
- // And changing the tag
- foreach (Word.Range tmpRange in oDocNew.StoryRanges)
- {
- tmpRange.Find.Text = "%UCZEN%";
- tmpRange.Find.Replacement.Text = students[i];
- tmpRange.Find.Wrap = Word.WdFindWrap.wdFindContinue;
- object replaceAll = Word.WdReplace.wdReplaceAll;
- tmpRange.Find.Execute(ref oMissing, ref oMissing, ref oMissing,
- ref oMissing, ref oMissing, ref oMissing, ref oMissing,
- ref oMissing, ref oMissing, ref oMissing, ref replaceAll,
- ref oMissing, ref oMissing, ref oMissing, ref oMissing);
- }
- // And adding a page break at the end if it's not the last student
- if (i < students.Length - 1)
- {
- object oPageBreak = Word.WdBreakType.wdPageBreak;
- oDocNew.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertBreak(ref oPageBreak);
- }
- }
- // we save the resulting document
- object FileName = Path.GetFullPath(@"..\..\Wynik.doc");
- oDocNew.SaveAs(ref FileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
- ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
- ref oMissing, ref oMissing, ref oMissing, ref oMissing);
- }
- finally
- {
- if (oWord != null)
- {
- // Close Word
- object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
- oWord.Quit(ref doNotSaveChanges, ref oMissing, ref oMissing);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment