Pages

Tuesday, November 13, 2012

Word Document Type Provider

I just published Word Document Type Provider on the F# 3.0 Sample Pack. The type provider uses the Office OpenXML SDK. In the template file "AA.docx", there are several MergeField fields in the document. The type provider reads these fields and show them as class property to the type.

The type provider type uses the following code to specify the template:

    type T = Samples.ShareInfo.TPTest.TPTestType<"AA.docx">

The AA.docx is treat as the template for this type provider. And the constructor get a file name which will be generated from the template.

    let t = T("MRXYZ.docx")

The above statement is to use the AA.docx template and generate the MRXYZ.docx file. The rest of the code is to set fields.

t.Person <- br="br" r.="r." xyz="xyz">t.ContactInformation <- br="br" com="com">t.MyCompany <- br="br" company="company">t.MyName <- br="br" lee="lee" ohn="ohn">t.NewProduct <- blockquote="blockquote" new="new" product="product">



Please make sure you do t.Close() to flush the content to the hard disk. The generated file MRXYZ.docx is located at the same folder as AA.docx. And the content of the file is


If you click "ABC Company"  or other fields, you can find the "Update Field" is disabled. You can use this approach to get the data from any data storage and export to Word Document.

For details, please download the source code from F# 3.0 Sample Pack. See the screenshot below:


According to a user's feedback, I added a new feature for this type provider. This feature will make sure all the fields are assigned a value. If there is a field missing, then the .Close function will generate an exception.

2 comments:

scypior said...

Gone are the times when the simpliest option was just to call 'Search and replace' via COM on MSWord instance;) (well, maybe it wasn't nice, but I did it).

Love to see new providers appearing.

chribben said...

Hi Tao, I just tried the sample and it worked fine. However, when running it with another document than the provided AA.docx it doesn't work, any ideas? More info: http://stackoverflow.com/questions/22363524/cant-get-the-f-word-typeprovider-to-work-for-custom-word-documents