Start Your First Python Project in 3 Steps: Grab Your Free Online Course Right Now!
The error I made in the past was writing documents by hand, which was more time-consuming and error-prone. Additionally, the document was of a more modest quality and never up to date.
The solution was to automate the generation of the documentation.
1. Opening and Closing a Word File from MATLAB
If you want to write data into a Word file, you first need to open it. The function below has been created to open a word file and to output a structure that will be used to identify the file you want to write on:
function fid = fopenWord(wordFile) word = actxserver('Word.Application'); word.Visible = 1; if ~exist(wordFile, 'file'); % create new document: fid.handle = invoke(word.Documents, 'Add'); invoke(fid.handle, 'SaveAs', [pwd '/' wordFile]); else % open existing document: fid.handle = invoke(word.Documents, 'Open', [pwd '/' wordFile]); end fid.actx = word; end
This function will:
- Open a Word file with the name given by the variable wordFile if the file already exists in the current folder.
- Open a new Word file with the name given by the variable wordFile if the file does not already exist.
When you are done with writing into the file, you then need to close it:
function fcloseWord(fid) handle = fid.handle; word = fid.actx; % save the Word file invoke(handle, 'Save'); % close Word word.Quit(); end
Below is an example of using the 2 functions. In this example, we create a new Word file, save it and close it, and then open the file as if you clicked on it from your computer.
clc % name of your file wordFile = 'myWordFile.doc'; % open your Word file fid = fopenWord(wordFile); %−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− % write into your word file %−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− % close your word file fcloseWord(fid); % open the file as if you clicked on it winopen(wordFile);
If you want a more advanced tutorial on how to read and write Word documents with MATLAB, I have an entire section about it in this small reference book: