Create a word document from Matlab

| categories: miscellaneous | View Comments

Create a word document from Matlab

Create a word document from Matlab

John Kitchin

Have you been wondering how to create a word document from Matlab that doesn't require the publish button? Below we look at a way to use Matlab for COM automation to create a word document and put text in it. I adapted the Perl code at http://www.adp-gmbh.ch/perl/word.html for this example. There is hardly any interesting output from any of these commands,

Contents

Create the word application

and make it visible

word = actxserver('Word.Application');
word.Visible = 1;

Add a new document and get the current selection

document = word.Documents.Add;
selection = word.Selection;

add text and paragraphs

selection.TypeText('Hello world. ');
selection.TypeText('My name is Professor Kitchin');
selection.TypeParagraph;
selection.TypeText('How are you today?');
selection.TypeParagraph;

Setting a Header

selection.TypeText('Big Finale');
selection.Style='Heading 1';
selection.TypeParagraph;

Modifying Header properties

H1 = document.Styles.Item('Heading 1')
H1.Font.Name = 'Garamond';
H1.Font.Size = 20;
H1.Font.Bold = 1;
H1.Font.TextColor.RGB=60000; % some ugly color green

selection.TypeParagraph
selection.TypeText('That is all for today!')
 
H1 =
 
	Interface.0002092C_0000_0000_C000_000000000046

Now we save the document

document.SaveAs2([pwd '/test.docx']);
word.Quit();

Summary

That is it! I wouldn't call this extra convenient, but if you have a need to automate the production of Word documents from a program, this is an approach that you can use. You may find http://msdn.microsoft.com/en-us/library/kw65a0we%28v=vs.80%29.aspx a helpful link for documentation of what you can do.

%  download test.docx 

% categories: Miscellaneous
blog comments powered by Disqus