Start Your First Python Project in 3 Steps: Grab Your Free Online Course Right Now!
Writing Data into a Word File
If you want to write data properly into a Word file, you need to be able to write this data as a heading, as plain text, or as text with a particular font, a particular size, or even a particular highlighting. In the function that follows, you can define the characteristics of the font by creating a structure with 3 fields:
- font.name: name of the font as it appears in Word (“Arial,” for example)
- font.size: size of the font as it appears in Word (10 for example)
- font.bold: use 1 to make the font bolded and 0 if you don’t want the font to be bolded
You can also not use this argument into the function. If you don’t, it will use your default Word configuration.
The value of the argument “type” can be:
- “Normal“, if you do not want your text to be a heading
- “section“, if you want your text to be the title of a section
- “subsection“, if you want your text to be the title of a subsection
function writeData(fid, data, type, font) word = fid.actx; selection = word.Selection; if strcmp(type, 'section') word.Selection.Style = 'Heading 1'; elseif strcmp(type, 'subsection') word.Selection.Style = 'Heading 2'; else word.Selection.Style = type; end if nargin>3 selection.Font.Name = font.name; selection.Font.Size = font.size; selection.Font.Bold = font.bold; end selection.TypeText(data); return
Likewise, you will probably not want to write all your text on a single line. The following function only uses the fid structure as the reference for your Word file. It simply goes to the next line and has to be used when the cursor cannot go down (e.g. when you are writing a title and there is no content below).
function newLine(fid) word = fid.actx; selection = word.Selection; selection.TypeParagraph; return
In this example, we open a Word file, write the desired data in the file and close the file. If you do not know how to open and close a file, see part 1 of this tutorial.
% name of your file wordFile = 'myWordFile.doc'; % open your Word file fid = fopenWord(wordFile); %−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− font.name = 'Arial'; font.size = 10; font.bold = 0; data = 'This is the First Section of my Word File'; writeData(fid, data, ’section’, font) newLine(fid) data = 'This is the First Subsection of my Word File'; writeData(fid, data, 'subsection', font) newLine(fid) data = 'This is the text I want to write in my Word file.'; writeData(fid, data, 'Normal', font) newLine(fid) data = 'This is the Second Subsection of my Word File'; writeData(fid, data, 'subsection', font) newLine(fid) data = 'This is the text I want to write in the second subsection of my Word file.'; writeData(fid, data, 'Normal', font) newLine(fid) %−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− % close your word file fcloseWord(fid); % open the file as if you clicked on it winopen(wordFile);
This example will generate the following Word file: