Thursday, December 19, 2013

NetOffice an MsWord class Wrapper


In order to produce a Word document without MsOffice installed, I recommend to use this suite of libraries, that are Open Source (http://netoffice.codeplex.com/). There are plenty of reasons that convincing me that this is a good  way to interact with MsOffice, I let you to check if these are good enough also for you. By the way I had prepared a C# Class with an example to try. This class wraps very typical functionalities in document generation.

These functions are simple and intuitive:

  • Open and Create a Document.
  • Writing
  • Attach a Picture
  • Generating a Table
  • Text Formatting  
Many other can be added and you can improve this class very easy as you prefer.
First of all you have to download the package on your pc (http://netoffice.codeplex.com/releases/view/70943) and install it, then it is enough to find the dlls mentioned below, and attach that to the project.


Please set the “Embed Interop Types” property to False.


In the example I have prepared, it is possible to find every specific functionalities I wrote before. So with very few code here the demonstration:


List lPersons = new List();
lPersons.Add(new Person("John","Anderson", 43));
lPersons.Add(new Person("Lorenz", "Bullock", 36));
lPersons.Add(new Person("Frank", "Carlson", 28));
lPersons.Add(new Person("Frederick", "Doson", 33));

WordWrapper oWord = new WordWrapper();

if (File.Exists(sFile))
  oWord.OpenDocument(sFile);
else
  oWord.CreateDocument(sFile, false);

oWord.AddPicture(sDir + "image.png", true);

oWord.SetFont("Arial", WdColor.wdColorDarkRed, 14, true);
oWord.WriteText("1. Hello World!");

oWord.PrintTable(lPersons);
            
oWord.Save();
oWord.CloseAndDispose();
oWord.ShowDocument(sFile);

One thing I appreciate more is that the API is Syntactically and semantically identical to the Microsoft Interop Assemblies so if you before had used Microsoft API this is “easy peasy lemon squeezy”! The first thing to do is to create an Application object and disable all messages:

public WordWrapper()
{
  moApp = new Word.Application();
  moApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
}

Once you have the Application Member moApp you can manipulate the Word Documents:

public void OpenDocument(string sFileName)
{
  if (moApp == null) return;
  msFileName = sFileName;
  moDoc = moApp.Documents.Open(sFileName);
}

Your Document is now open and can be used to interact.

public void AddPicture(
string sFileName, 
bool bNewParagraph = true, 
int iWidth = 0, 
int iHeight = 0)
{
  if (!File.Exists(sFileName)) return;
  if (moApp == null) return;
  if (moDoc == null) return;

  var shape = moApp.Selection.InlineShapes.AddPicture(sFileName, true, true);

  if (iWidth > 0)
    shape.Width = iWidth;
  if (iHeight > 0)
    shape.Height = iHeight;

  if (bNewParagraph)
    moApp.Selection.TypeParagraph();
}

download here!