C#How To Read And Write Microsoft Word Documents

Do you like this?

Summary:
This short post shows you how to modify word documents using C#


Content:

Firstly you need to add Word library as follows: C# How To Read Write Word Documents Step 1

Then you have to change the property "Embed Interop Type" to False: C# How To Read Write Word Documents Step 2

Below is a sample code to modify word documents. What it does is open a word document with the given file path, then it goes through all the tables and their cells and append the text "test" at the end.

using Word= Microsoft.Office.Interop.Word;

static void changeTableCellText(object filePath)
{
	object readOnly = false;
	object isVisible = true;
	object missing = System.Reflection.Missing.Value;
	Word.ApplicationClass oWordApp = new Word.ApplicationClass();

	Word.Document oWordDoc = oWordApp.Documents.Open(ref filePath,
								ref missing, ref readOnly,
								ref missing, ref missing, ref missing,
								ref missing, ref missing, ref missing,
								ref missing, ref missing, ref isVisible,
								ref missing, ref missing, ref missing);

	oWordDoc.Activate();


	foreach(Word.Table table in oWordDoc.Tables){
		foreach(Word.Cell cell in table.Range.Cells){
			Word.Range cell_range= cell.Range;
			cell_range.InsertAfter("test");
		}
	}
	
	oWordDoc.Save();
	oWordApp.Application.Quit(ref missing, ref missing, ref missing);
}

 
comments powered by Disqus