About Me

My Photo
Ireland
Hello, my name is Cathal Coffey. I am best described as a hybrid between a developer and an adventurer. When I am not behind a keyboard coding, I am hiking and climbing the beautiful mountains of my home country Ireland. I am a full time student studying Computer Science & Software Engineering at the National University of Ireland Maynooth. I am finishing the final year of a 4 year degree in September 2009. I am the creator of an open source project on codeplex.com called DocX. At the moment I spend a lot of my free time advancing DocX and I enjoy this very much. My aim is to build a community around DocX and add features based on requests from this community. I really enjoy hearing about how people are using DocX in their work\personal projects. So if you are one of these people, please send me an email. Cathal coffey.cathal@gmail.com

Monday, June 14, 2010

Cathal: Why did you create DocX?

Before I created the OpenSource library “DocX”, there were two methods by which a .docx document could be generated programmatically. This blog post demonstrates each method in turn by generating a simple HelloWorld document. 

After experiencing both methods for document creation I hope you will agree that DocX is a interesting alternative. DocX was designed with simplicity in mind. It dose not require the user to have any knowledge of how .docx documents are stored or organised internally.

Method 1: HelloWorld using Office Interop

Make sure that you have added a reference to

1) Microsoft.Office.Interop.Word (version 12.0.0.0)

image

OfficeInterop HelloWorld
  1. using System;
  2. using Microsoft.Office.Interop.Word;
  3. using System.Reflection;
  4. using System.IO;
  5.  
  6. namespace OfficeInterop
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             // Get the path of the executing assembly.
  13.             string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  14.  
  15.             // The location to save the file.
  16.             Object oSaveAsFile = (Object)(path + @"\Test.docx");
  17.  
  18.             // Object of Missing "Null Value".
  19.             Object oMissing = System.Reflection.Missing.Value;
  20.  
  21.             // Object of false.
  22.             Object oFalse = false;
  23.  
  24.             // Create object of Word and Document.
  25.             Application oWord = new Application();
  26.             Document oWordDoc = new Document();
  27.  
  28.             // Don't display Word.
  29.             oWord.Visible = false;
  30.  
  31.             // Add a new document.
  32.             oWordDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
  33.             
  34.             // Enter some text with the font Arial Black.
  35.             oWord.Selection.Font.Name = "Arial Black";
  36.             oWord.Selection.TypeText("Hello World");
  37.  
  38.             // Save the document.
  39.             oWordDoc.SaveAs
  40.             (
  41.                 ref oSaveAsFile, ref oMissing, ref oMissing, ref oMissing,
  42.                 ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing,
  43.                 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
  44.                 ref oMissing, ref oMissing
  45.             );
  46.  
  47.  
  48.             // Close the file.
  49.             oWordDoc.Close(ref oFalse, ref oMissing, ref oMissing);
  50.              
  51.             // Quit Word.exe
  52.             oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
  53.         }
  54.     }
  55. }

 

Method 2: HelloWorld using the OOXML SDK

Make sure that you have added a reference to both

1) DocumentFormat.OpenXml (version 2.0.5022.0)
2) WindowsBase (version 3.0.0.0)

image

OOXML HelloWorld
  1. using DocumentFormat.OpenXml.Packaging;
  2. using DocumentFormat.OpenXml.Wordprocessing;
  3. using DocumentFormat.OpenXml;
  4.  
  5. namespace OOXML
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             // Create a package.
  12.             WordprocessingDocument doc =
  13.             WordprocessingDocument.Create
  14.             (
  15.                 @"Test.docx",
  16.                 WordprocessingDocumentType.Document
  17.             );
  18.  
  19.             // Create a main document part and add it to the package.
  20.             MainDocumentPart mainPart = doc.AddMainDocumentPart();
  21.             mainPart.Document = new Document();
  22.             
  23.             // Create some content.
  24.             Text textFirstLine = new Text("Hello World");
  25.             Run run = new Run(textFirstLine);
  26.             Paragraph para = new Paragraph(run);
  27.            
  28.             // Apply a font.
  29.             RunProperties runProp = new RunProperties();
  30.             RunFonts runFont = new RunFonts();
  31.             runFont.Ascii = "Arial Black";
  32.             runProp.Append(runFont);
  33.             run.PrependChild<RunProperties>(runProp);
  34.             // Add the content into the document.
  35.             Body body = new Body(para);
  36.             mainPart.Document.Append(body);
  37.             
  38.             /* Save and close */
  39.             mainPart.Document.Save();
  40.             doc.Close();
  41.         }
  42.     }
  43. }

HelloWorld using DocX

Make sure that you have added a reference to

1) DocX (version 1.0.0.9)
2) System.Drawing (version 2.0.0.0)

image

DocX HelloWorld
  1. using System;
  2. using Novacode;
  3. using System.Drawing;
  4.  
  5. namespace DocXHelloWorld
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             using (DocX document = DocX.Create("Test.docx"))
  12.             {
  13.                 // Add a new Paragraph to the document.
  14.                 Paragraph p = document.InsertParagraph();
  15.                 
  16.                 // Append some text.
  17.                 p.Append("Hello World").Font(new FontFamily("Arial Black"));
  18.  
  19.                 // Save the document.
  20.                 document.Save();
  21.             }
  22.         }
  23.     }
  24. }

9 comments:

  1. I need help here!
    I need to open a word file stored on the server using asp.net but using VB and not C#.
    I tried to use the code for editing the file but it gives and error saying
    "Novacode.docX.Private Sub New(document as Novacode.DocX, xml As System.Xml.Linq.XElement)' is not accessible in this context because ot os 'Private'.
    Please help...

    ReplyDelete
  2. Mandy, you may want to try converting the c# code above to VB using an online convertor, such as http://www.developerfusion.com/tools/convert/csharp-to-vb/

    ReplyDelete
  3. how can i save word as pdf using docx?

    ReplyDelete
  4. Cathal Coffey , Thank you for your blog , it is helpful

    ReplyDelete
  5. is there a way to integrate an audio file into an existing document using DocX?

    ReplyDelete
  6. I love it,Excellent article.I am decide to put this into use one of these days.Thank you for sharing this.To Your Success!
    _____________________________________________________________________________

    Rc Helicopter Parts|Rc Helicopter|Mini Rc Helicopter

    ReplyDelete
  7. hi, I can edit in the browser a file created with docX.dll, summing up ... I'm trying to edit the file in an asp.net page. thanks ... carlitolima@hotmail.com, i am from Brasil..

    ReplyDelete
  8. I appreciate this, but as long as there is no Style support, what's the use? Anyone who works with Word (and document production in general) surely would only ever want to work with Styles rather than setting fonts and such manually?

    ReplyDelete
  9. Hi, I am using vb in my asp.net project. I have 2 problems
    1. Where should I place the word file when I am using DocX.load?
    2. I can't create paragraph, Visual Studio say "Paragraph is ambiguous". What can I do?

    Thanks for your support

    ReplyDelete