This is a mirror of official site: http://jasper-net.blogspot.com/

Manipulate Docx with C# without Microsoft Word installed with Open XML SDK

| Tuesday, June 15, 2010
With the Open XML SDK you can edit docx without having Microsoft Word installed.

In this particular situation, I'm editing the custom properties of the docx, which are commonly used to store some application's info to further use, or even some add-in that we developed as well.

Using the code

This article is really simple, it's purpose is to spread the word, is just showing you what to do based on MSDN.

For starters, the discovery was when I found the Open XML SDK that allows me to manipulate my Word document without having office installed on the server running my application, which is a major breakthrough!
The code I used to add custom properties was taken from MSDN and I show it to you here:

public bool WDSetCustomProperty(string docName, string propertyName, object propertyValue, PropertyTypes propertyType)
   {
     const string documentRelationshipType =
       "http://schemas.openxmlformats.org/officeDocument/" +
       "2006/relationships/officeDocument";
     const string customPropertiesRelationshipType =
       "http://schemas.openxmlformats.org/officeDocument/" +
       "2006/relationships/custom-properties";
     const string customPropertiesSchema =
       "http://schemas.openxmlformats.org/officeDocument/" +
       "2006/custom-properties";
     const string customVTypesSchema =
       "http://schemas.openxmlformats.org/officeDocument/" +
       "2006/docPropsVTypes";

     bool retVal = false;
     PackagePart documentPart = null;
     string propertyTypeName = "vt:lpwstr";
     string propertyValueString = null;

     //  Calculate the correct type.
     switch (propertyType)
     {
       case PropertyTypes.DateTime:
         propertyTypeName = "vt:filetime";
         //  Make sure you were passed a real date,
         //  and if so, format in the correct way. The date/time
         //  value passed in should represent a UTC date/time.
         if (propertyValue.GetType() == typeof(System.DateTime))
         {
           propertyValueString = string.Format("{0:s}Z",
             Convert.ToDateTime(propertyValue));
         }
         break;

       case PropertyTypes.NumberInteger:
         propertyTypeName = "vt:i4";
         if (propertyValue.GetType() == typeof(System.Int32))
         {
           propertyValueString =
             Convert.ToInt32(propertyValue).ToString();
         }
         break;

       case PropertyTypes.NumberDouble:
         propertyTypeName = "vt:r8";
         if (propertyValue.GetType() == typeof(System.Double))
         {
           propertyValueString =
             Convert.ToDouble(propertyValue).ToString();
         }
         break;

Read more: Codeproject

Posted via email from .NET Info

0 comments: