⌘BABAKOV.NET Let's code!
100% [light] [ru]

Examples of Changing Word Documents from C#

    Recently, I've had to work with Word documents from C#. I'd say it's a decent mechanism for generating simple reports. It's quite convenient - since Word is often installed on most user computers, there's no need to install additional components, such as Crystal Reports (they're good, but when you need something very simple, it's better without them).
    Additionally, I'd like to mention that if for some reason the necessary components of the Word program are missing on the client machine, it remains almost unnoticed, since they are installed automatically on the first access (which surprised me very much, but this is about the way of accessing Word documents - described below).

    Below are two examples of working with a Word document. The first illustrates replacing text in a document - convenient to use when auto-filling contracts and inserting necessary values. The second illustrates filling tables - convenient to use when creating simple reports.

Example #1 (Replacement)

//Создаём новый Word.Application
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

//Загружаем документ
Microsoft.Office.Interop.Word.Document doc = null;

	object fileName = "Здесь путь до файла Word формата *.doc";
	object falseValue = false;
        object trueValue = true;
        object missing = Type.Missing;

doc = app.Documents.Open(ref fileName, ref missing, ref trueValue, 
ref missing, ref missing, ref missing, ref missing, ref missing, 
ref missing, ref missing, ref missing, ref missing, ref missing, 
ref missing, ref missing, ref missing);

//Теперь у нас есть документ который мы будем менять.

//Очищаем параметры поиска
app.Selection.Find.ClearFormatting();
app.Selection.Find.Replacement.ClearFormatting();

//Задаём параметры замены и выполняем замену.
object findText = "<Что меняем>";
object replaceWith = "<На что меняем>";
object replace = 2;

app.Selection.Find.Execute(ref findText, ref missing, ref missing, ref missing, 
ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith, 
ref replace, ref missing, ref missing, ref missing, ref missing);



//Открываем документ для просмотра.
app.Visible = true;



Example #2 (Filling a table)

//Создаём новый Word.Application
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

//Загружаем документ
Microsoft.Office.Interop.Word.Document doc = null;

	object fileName = "Здесь путь до файла Word формата *.doc";
	object falseValue = false;
        object trueValue = true;
        object missing = Type.Missing;

doc = app.Documents.Open(ref fileName, ref missing, ref trueValue, 
ref missing, ref missing, ref missing, ref missing, ref missing, 
ref missing, ref missing, ref missing, ref missing, ref missing, 
ref missing, ref missing, ref missing);

//Указываем таблицу в которую будем помещать данные (таблица должна существовать в шаблоне документа!)
Microsoft.Office.Interop.Word.Table tbl = app.ActiveDocument.Tables[1];

//Заполняем в таблицу - 10 записей.

for (int i=1; i<11; i++)
{
	tbl.Rows.Add(ref missing);//Добавляем в таблицу строку.
	//Обычно саздаю только строку с заголовками и одну пустую для данных.
        tbl.Rows[i + 1].Cells[1].Range.Text = "Запись №"+i.ToString();
        tbl.Rows[i + 1].Cells[2].Range.Text = "Запись №"+i.ToString();
        tbl.Rows[i + 1].Cells[3].Range.Text = "Запись №"+i.ToString();
 
}

//Открываем документ для просмотра.
app.Visible = true;



That's all. I hope this information will be useful to someone.

P.S. almost forgot.
For this to work,
you need to add a Reference: Microsoft.Office.Interop.Word.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.