1. Access field values

Access Word document fields

Version:

You can use the Sitecore.Data.Fields.WordDocumentField class to access the value of a Word document field. You can use the Sitecore.Data.Fields.WordDocumentField.Html property to access the HTML representation of the field value. You can use the Sitecore.Data.Fields.WordDocumentField.PlainText property to access the plain text representation of the field value.

You can use the Sitecore.Data.Fields.WordDocumentField.Styles property to access the Cascading Style Sheet code associated with that HTML. For example, you can implement a Web control based on the following example that outputs the styles and HTML of a Word Document field:

namespace Sitecore.Sharedsource.Web.UI.WebControls
{

    using System;
    using System.Text.RegularExpressions;

    public class RenderWordDocumentFieldRenderer : Sitecore.Web.UI.WebControl
    {

        public string FieldName { get; set; }

        protected override void DoRender(System.Web.UI.HtmlTextWriter output)
        {
            Sitecore.Data.Items.Item item = this.GetItem();

            if (this.FieldName == null || item == null) 
            {
                return;
            }

            Sitecore.Data.Fields.WordDocumentField wordField = item.Fields["WordField"];

            if (wordField == null || wordField.BlobId == Sitecore.Data.ID.Null || Regex.IsMatch(wordField.PlainText, "^\\s*$"))
            {
                return;
            }

            output.WriteLine(String.Format("<style type=\"text/css\">{0}</style>", wordField.Styles));

            output.WriteLine(Sitecore.Web.UI.WebControls.FieldRenderer.Render(item, wordField.InnerField.Name));
            }
        }
}

You can use the Sitecore.WordOCX.WordOCXUrlManager.GetDownloadLink method to retrieve a URL that provides access to the value of a Word Document field as a Word Document (.docx file).

For example, to retrieve a URL to access the Word Document field named WordDocument in the context item as a Word Document file:

Sitecore.Data.Items.Item item = Sitecore.Context.Item;

Sitecore.Data.Fields.WordDocumentField wordField = item.Fields["WordDocument"];

if (wordField != null && wordField.BlobId != Sitecore.Data.ID.Null && !Regex.IsMatch(wordField.PlainText, "^\\s*$"))
{
    Dictionary<string, string> parameters = new Dictionary<string, string>();

    parameters["db"] = item.Database.Name;

    parameters["blobId"] = wordField.BlobId.ToString();

    Sitecore.WordOCX.WordOCXUrlManager wordManager =

    new Sitecore.WordOCX.WordOCXUrlManager(parameters);

    string url = wordManager.GetDownloadLink();
}
If you have suggestions for improving this article, let us know!