-
Notifications
You must be signed in to change notification settings - Fork 0
/
wordserver.m
1446 lines (1439 loc) · 82.5 KB
/
wordserver.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
classdef wordserver < handle
%{
Class to access Microsoft Word documents.
This is an extension of 'wordreport' by Laurent Vaylet
Main changes:
converted code to a class
included/expanded inclusion of figures and tables with captions and bookmarks
included references to figures and tables
included header and footer
changed handling of arguments
included all wd constants (that are used) in one function (with translate function)
Copyright 2017 Han Oostdijk MIT License
Version: 1.0 Date 10feb2017
Information about the Microsoft Word object model can be found e.g. in
https://msdn.microsoft.com/en-us/library/office/ff837519.aspx
https://msdn.microsoft.com/en-us/library/office/aa211923(v=office.11).aspx
Acknowledgement : copied all code from 'wordreport' in this class:
https://nl.mathworks.com/matlabcentral/fileexchange/17953-wordreport
Author: Laurent Vaylet
E-mail: [email protected]
Release: 1.0
Release date: 12/10/07
Some extra functions were added to 'wordreport' by Dmytro Makogon
Todo :
SetTableColWidth : allow specification of specific columns
SetTableColAlign : allow specification of specific columns
All functions with exception of close_doc, saveas_doc, save_doc, activate_doc,
set_saved_doc and SelectionSetFont have a structure od with default parameters.
These parameters can be overwritten in three ways:
with a structure optionally followed by overwriting name-value pairs
with a cell array optionally followed by overwriting name-value pairs
with name-value pairs
functions :
wordserver : Starts word activex server and sets default style and prefix for headers
parameters:
'normal' (default 'normal')
'heading' (default 'Heading')
delete : Destructor for class
no parameters
quit : Quit the Word application
no parameters
set_visible : make Word (in-)visible
parameters:
'visible' (default true)
open_doc : Open a new or existing word document
parameters:
'file_name' (default '')
close_doc : Close document without saving first
parameters:
the document object that is to be closed
saveas_doc : Save document (with another name?)
parameters:
the document object that is to be closed
'file_name' (default is the old file name)
save_doc : Save document (under its old name)
parameters:
the document object that is to be closed
activate_doc : Make a document the active one
parameters:
the document object that is to be closed
get_active_doc : Retrieve the active document object
no parameters
set_saved_doc : Indicate that the document does not need to be saved
no parameters
AddParagraph : Add a paragraph at the end of the document
parameters:
'color' (default 'wdAuto') : color of paragraph as one of enum WdColorIndex
AddSymbol : Add a symbol represented by an integer
parameters:
'symbol' (default 176) : an integer found in the Insert/Symbol menu
SelectionSetFont : Set font attributes for selection
parameters:
one or more of the following fields without defaults but given with an example
(only in struct of name-value pair format)
'Name' 'Arial'
'Size' 9
'Bold' false
'Italic' false
'Underline' false
'StrikeThrough' false
'ColorIndex' 'wdAuto'
'DoubleStrikeThrough' false
'Superscript' false
'Subscript' false
SelectionSetAlignment : Set alignment for selection
parameters:
'align' (default wdAlignParagraphCenter) : alignment one of enum WdParagraphAlignment
SelectionInsertText : Insert text over or besides selection
parameters:
'text' (default '') : text to insert
'lineBreaks' (default [0,0]) : vector with line breaks before and after text
'color' (default 'wdAuto') : color to use as one of enum WdColorIndex
'fun' (default 'InsertAfter') : function to use (TypeText, InsertBefore or InsertAfter )
'collapse' (default true) : Collapse section after insert: true (yes: at end ), false (no)
InsertTable : Insert a table in the document with caption and bookmark
parameters:
'dataCell' (default []) : (character) data to insert
'lineBreaks' (default [1,1]) : vector with line breaks before and after table
'bmn', (default '') : bookmark name to associate with table
'captitle' (default '') : caption to be given to table
'cappos' (default 'wdCaptionPositionBelow') : position of caption: one of enum WdCaptionPosition
'align' (default 'wdAlignRowCenter') : alignment one of enum WdRowAlignment
'title' (default '') : title of table (in table properties)
'descr' (default '') : description of table (in table properties)
InsertFigure : Insert a figure in the document
parameters:
'what' (default []) : graphics handle or graphics file name
'lineBreaks' (default [1,1]) : vector with line breaks before and after figure
'bmn', (default '') : bookmark name to associate with figure
'captitle' (default '') : caption to be given to figure
'cappos' (default 'wdCaptionPositionBelow') : position of caption: one of enum WdCaptionPosition
'align' (default 'wdAlignRowCenter') : alignment one of enum WdRowAlignment
'title' (default '') : title of figure (in figure properties)
'descr' (default '') : description of figure (in figure properties)
InsertXRefCaption : Insert cross reference to a caption
parameters:
'bmn', (default '') : bookmark name associated with table, figure, ...
'reftype' (default 'wdCaptionTable') : ReferenceType one of enum WdReferenceKind
'refkind' (default 'wdOnlyLabelAndNumber') : ReferenceKind one of enum WdReferenceKind
'ashyper' (default true) : Insert as hyperlink
SetTableColWidth : Set column widths for table
parameters:
'columns' (default []) : column numbers to change ([] is all)
'widths' (default []) : widths in cm or as a percentage
'width_type' (default 'wdPreferredWidthPoints'): width type one of enum WdPreferredWidthType
SetTableColAlign : Set alignment for columns for table
parameters:
'columns' (default []) : column numbers to change ([] is all)
'align' (default []) : cell array with WdParagraphAlignment constants
SelectTableColumn : Select a column of a table
parameters:
'colnr' (default 1) : number of column to select
SelectTableRow : Select a row of a table
parameters:
'rownr' (default 1) : number of row to select
SelectTableCell : Select a cell of a table
parameters:
'rownr' (default 1) : row number of the cell to select
'colnr' (default 1) : column number of the cell to select
GetTable : Get data from current table
parameters:
'ignoreHeader' (default true) : ignore row header ?
WriteTable : Write data to current table
parameters:
'data' (default []) : (character) data to write to table
'fstRow' (default 1) : number of the first row to write to
'fstCol' (default 1) : number of the first column to write to
SetRowNumb : Change number of rows in current table
parameters:
'nbRows' (default 1) : set number of rows
SetColumnNumb : Change number of cols in current table
parameters:
'nbCols' (default 1) : set number of columns
SetStyle : Set current text style, used later by SelectionInsertText
parameters:
'style' (default obj.normal) : set style to use
SelectionInsertBreak : Insert a break of specified type at start of selection
parameters:
'breaktype' (default 'wdPageBreak') : one of enum WdBreakType
Goto : Jump to specified location in document
parameters:
'what' (default 'wdGotoBookmark') : one of enum enum WdGoToItem
'which' (default 'wdGotoAbsolute') : one of enum enum WdGoToDirection
'count' (default 1) : number of what
'name' (default '') : name of what
'delete' (default false) : delete contents indicated selection
FindText : Find text in document
parameters:
'textToFind' (default '') : text to find
'forward' (default true) : forward (true) or backward (false)
'replacement' (default '') : number of what
'name' (default '') : replacement text
'findopts' (default struct()) : find options that overwrite the default find options:
'wdReplace' (default 'wdReplaceNone') :
'wdFindwrap' (default 'wdFindContinue') :
'MatchCase' (default false) :
'MatchWholeWord' (default false) :
'MatchWildcards' (default false) :
'MatchSoundsLike' (default false) :
'MatchAllWordForms' (default false) :
'Format' (default false) :
Select : Extend or move selection 'right', 'left', 'home' or 'end' , 'up' or 'down'
parameters:
'direction' (default 'right') : direction ('right', 'left', 'home' or 'end' , 'up', 'down'
'unit' (default 'wdCharacter') : unit (one of enum WdUnits)
'count' (default 1) : number of 'units'
'extend' (default 'wdMove') : 'wdMove' or 'wdExtend'
CreateTOC : Create the table of contents, list of figures or list of tables
parameters:
'type' (default 'TOC') : type TOC, Figure or Table
'text' (default 'Table of Contents) : text to print above TOC or list
'fontstruct' (default []) : struct for use in SelectionSetFont to print text
'tableader' (default 'wdTabLeaderDots') : enum WdTabLeader
'include_label' (default true) : include label in list of figure or table
'UseHeadingStyles' (default true) : forced to false for Figure and Table
'UpperHeadingLevel' (default 1) : highest level to include in TOC
'LowerHeadingLevel' (default 3) : lowest level to include in TOC
'UseFields' (default false) :
'TableID' (default '') :
'RightAlignPageNumbers' (default true) :
'IncludePageNumbers' (default true) :
'AddedStyles' (default '') :
'UseHyperlinks' (default true) :
'HidePageNumbersInWeb' (default true) :
'UseOutlineLevels' (default false) :
UpdateTOC : Update the Table of Contents
parameters:
'upd_pn_only' (default false) : update page numbers only ?
AddHeaderFooter : Add header or footer to the document
parameters:
'align' (default 'wdCenter') : alignment one of WdAlignmentTabAlignment
'infooter' (default true) : true when in footer otherwise false
'pagetxt' (default 'page ') : prefix for page number
'inc_page' (default true) : true when page number is to be included
'inc_tot' (default true) : true when total number of pages isto be included
'inctxt' (default ' of ') : prefix for total number
PrintMethods : Print all available methods for a Word ActiveX object
parameters:
'category' (default 'Application') : object type for which methods are to be listed
'headingString' (default [obj.heading,' 2']) : heading style for this list
%}
properties
w % handle to activex word server
currentStyle % style to use for next action
wd_alpha_list % word constants (alpha)
wd_num_list % word constants (numeric)
normal % default style (in English Normal)
heading % default header prefix (in English Heading)
end
methods
function obj = wordserver(varargin) % constructor for class
% WORDSERVER Starts word activex server and sets default style and prefix for headers
od = struct( ... % default constants
'normal', 'Normal', ... % for default style
'heading', 'Heading' ) ; % for prefix of header
obj.w = wordserver. ... % try to reuse existing server
actxserver2('Word.Application');
[obj.wd_alpha_list,obj.wd_num_list] = ... % convert the array with
wordserver.wd_def_const() ; % word constants
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
obj.normal = od.normal ; % set the name of the default style
obj.heading = od.heading ; % set the prefix for headings
obj.currentStyle = obj.normal; % set current style to the default style
end
function delete(obj)
% DELETE Destructor for wordserver class
try
quit(obj)
catch
end
end
function quit(obj)
% QUIT Quit the Word application
invoke(obj.w, 'Quit'); % quit the Word application
delete(obj.w); % free storage related to server
end
function set_visible(obj,varargin)
%SET_VISIBLE make Word (in-)visible
od = struct( ... % defaults for arguments
'visible', true ... % make Word (in-)visible
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
set(obj.w,'Visible',od.visible); % make Word visible or not
end
function doc = open_doc(obj,varargin)
%OPEN_DOC Open a new or existing word document
od = struct( ... % defaults for arguments
'file_name', '' ... % file name
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h =obj.w ;
try
doc = invoke(h.Documents, ... % try to open document as
'Open', od.file_name); % existing file
catch % when this fails
doc = invoke(h.Documents,'Add'); % open a new file
if numel(regexp(od.file_name,'docx$')) > 0 % test extension
file_type = ... % docx extension
obj.wd2num('wdFormatXMLDocument') ;
else
file_type = ... % doc extension
obj.wd2num('wdFormatDocument97');
end
SaveAs2(doc,od.file_name,file_type) % save new file as doc or docx file
end
end
function close_doc(~,doc)
%CLOSE_DOC Close document without saving first
doc.Saved = true; % indicate that it is already saved
doc.Close() ; % close the file
end
function saveas_doc(~,doc,varargin)
%SAVEAS_DOC Save document (with another name?)
od = struct( ... % defaults for arguments
'file_name', doc.FullName ... % file name
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
invoke(doc, 'SaveAs2', od.file_name); % save it with the derived name
end
function save_doc(~,doc)
%SAVE_DOC Save document (under its old name)
invoke(doc, 'Save'); % save document (under its old name)
end
function doc = activate_doc(~,doc)
% ACTIVATE_DOC Make a document the active one
doc.Activate() ; % make a document the active one
end
function doc = get_active_doc(obj)
% GET_ACTIVE_DOC Retrieve the active document object
doc = obj.w.ActiveDocument ; % retrieve the active document
end
function set_saved_doc(~,doc)
% SET_SAVED_DOC Indicate that the document does not need to be saved
doc.Saved = 1; % indicate that the document does not need to be saved
end
function AddParagraph(obj,varargin)
% ADDPARAGRAPH Add a paragraph at the end of the document
od = struct( ... % defaults for arguments
'color', 'wdAuto' ... % color of paragraph as one of enum WdColorIndex
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ; % actxserver handle
par = h.ActiveDocument.Paragraphs.Add() ; % add a new paragraph at end of document
par = par.Next() ; % point to new paragraph (?? apparently needed)
par.Range.Style = obj.currentStyle ; % give the paragraph the current style
h.Selection.Start = par.Range.Start ; % set the selection to the whole range
h.Selection.End = par.Range.End ; % of the paragraph (next formatting does not work for Range?)
h.Selection.ClearFormatting() ; % remove all formatting from the selection
h.Selection.Style = obj.currentStyle ; % give the selection the current style
h.Selection.Font.ColorIndex = ... % give the font of the selection the chosen color
obj.wd2num(od.color) ;
end %AddParagraph
function AddSymbol(obj,varargin)
% ADDSYMBOL Add a symbol represented by an integer
% Integer can be found in the Insert/Symbol menu
% e.g. degree symbol = xB0 = 176
od = struct( ... % defaults for arguments
'symbol',176 ... % symbol
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
obj.w.Selection.InsertSymbol(od.symbol); % insert in selection
end % AddSymbol
function SelectionSetFont(obj,varargin)
% SELECTIONSETFONT Set font attributes for selection
% varargin is a structure with one or more of the following fields
% defopts = struct( ...
% 'Name', 'Arial' , ...
% 'Size', 9 , ...
% 'Bold', false , ...
% 'Italic', false , ...
% 'Underline', false , ...
% 'StrikeThrough', false , ...
% 'ColorIndex', 'wdAuto' , ...
% 'DoubleStrikeThrough', false , ...
% 'Superscript', false , ...
% 'Subscript', false ) ;
od = struct() ;
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
selectionfont = obj.w.Selection.Font ; % font object of the selection
fn = fieldnames(od) ; % specified options
for f = fn' % for each of the options
if strcmpi(f{1},'ColorIndex') % if this option is related to the ColorIndex
cc =od.(f{1}) ; % copy the ColorIndex constant
selectionfont.ColorIndex = ... % set the option to the translated constant
obj.wd2num(cc) ;
else
selectionfont.(f{1}) = od.(f{1}); % set the option to the specified value
end
end
end % SelectionSetFont
function SelectionSetAlignment(obj,varargin)
% SELECTIONSETALIGNMENT Set alignment for selection
od = struct( ... % defaults for arguments
'align','wdAlignParagraphCenter' ... % alignment one of enum WdParagraphAlignment
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
obj.w.Selection.ParagraphFormat. ... % alignment for selection
Alignment = obj.wd2num(od.align) ;
end % SelectionSetAlignment
function SelectionInsertText(obj,varargin)
% SELECTIONINSERTTEXT Insert text over or besides selection
od = struct( ... % defaults for arguments
'text', '', ... % text to insert
'lineBreaks', [0,0], ... % vector with line breaks before and after text
'color', [], ... % color to use as one of enum WdColorIndex
'fun', 'InsertAfter', ... % function to use (TypeText, InsertBefore or InsertAfter )
'collapse',true ... % Collapse section after insert: true (yes: at end ), false (no)
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ; % actxserver handle
userOvertype = h.Options.Overtype ; % save Overtype option
h.Options.Overtype = false ; % Make sure Overtype is turned off.
switch h.Selection.Type % depending on selection type
case 'wdSelectionIP' % insertion point
h.Selection.TypeText(od.text) % add the text
obj.Select({'Left','wdCharacter', ...% and select it
numel(od.text),'wdExtend'})
insert_done = true ; % indicate insertion is done
case 'wdSelectionNormal' % range selected
switch od.fun % insert text with selected function
case 'InsertBefore'
h.Selection.InsertBefore(od.text);
case 'TypeText'
h.Selection.Text=od.text;
case 'InsertAfter'
h.Selection.InsertAfter(od.text);
end
insert_done = true ; % indicate insertion is done
otherwise
insert_done = false ; % indicate insertion is not done
end
h.Options.Overtype = userOvertype ; % reset option to previous value
if insert_done % if insertion was done
for k = 1:od.lineBreaks(1)
h.Selection. ... % insert paragraph breaks before insertion
InsertParagraphBefore;
end
for k = 1:od.lineBreaks(2)
h.Selection. ... % insert paragraph breaks after insertion
InsertParagraphAfter;
end
h.Selection.Style = obj.currentStyle; % give selection the current style
if ~isempty(od.color)
h.Selection.Font.ColorIndex = ...
obj.wd2num(od.color) ; % give font the indicated color
else
h.Selection.Font.ColorIndex = ...
obj.wd2num('wdAuto') ; % give font the default color
end
if od.collapse
h.Selection.Collapse( ... % collapse selection at end
obj.wd2num('wdCollapseEnd'));
end
end
end %SelectionInsertText
function varargout = InsertTable(obj,varargin)
% INSERTTABLE Insert a table in the document with caption and bookmark
od = struct( ... % defaults for arguments
... 'dataCell', {'1', '2'; '3', '4'}, ... % data
'dataCell', [], ... % (character) data to insert
'lineBreaks', [1,1], ... % vector with number of line breaks before and after table
'bmn', '', ... % bookmark name to associate with table
'captitle', '', ... % caption to be given to table
'cappos', 'wdCaptionPositionBelow', ... % position of caption: one of enum WdCaptionPosition
'align', 'wdAlignRowCenter', ... % alignment one of enum WdRowAlignment
'title', '' , ... % title of table (in table properties)
'descr', '' ... % description of table (in table properties)
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ; % actxserver handle
[nbRows, nbCols] = size(od.dataCell);
for k = 1:od.lineBreaks(1)
h.Selection.TypeParagraph ; % Line breaks before table
end
% Create the table and set properties
newtab = h.ActiveDocument.Tables.Add( ...
h.Selection.Range, nbRows, nbCols, ...
obj.wd2num('wdWord9TableBehavior'), ... % Enables AutoFit
obj.wd2num('wdAutoFitContent')); % AutoFitContent
if numel(od.title) > 0
newtab.Title = od.title ; % set title when specified
end
if numel(od.descr) > 0
newtab.Descr = od.descr ; % set description when specified
end
align1 = obj.wd2num(od.align) ; % translate table alignment
newtab.Rows.Alignment = align1 ; % apply to tables
if nargout > 0
varargout{1} = newtab ; % return table object if requested
end
obj.SetStyle({obj.normal}); % set current style to 'Normal'
% Write data into table
for r = 1:nbRows
for c = 1:nbCols
obj.SelectionInsertText({od.dataCell{r, c}, ... % Write data into current cell
[0, 0],[],'TypeText'});
if(r*c == nbRows*nbCols)
h.Selection.MoveDown; % Done, leave the table
else
h.Selection.MoveRight; % Move on to next cell
end
end
end
for k = 1:od.lineBreaks(2)
h.Selection.TypeParagraph ; % Line breaks after table
end
if numel(od.bmn) > 0 % if bookmark name is specified
h.ActiveDocument.Bookmarks.Add ... % create bookmark for table range
(od.bmn,newtab.Range);
end
if numel(od.captitle) > 0 % if caption is specified
% Create 'Table' caption below or above table
r = newtab.Range ; % range of this table
switch od.cappos
case 'wdCaptionPositionAbove'
dir2cap = 'up' ;
case 'wdCaptionPositionBelow'
dir2cap = 'down' ;
r.Collapse( ... % collapse table range at end
obj.wd2num('wdCollapseEnd'));
end
r.InsertCaption('Table', ... % insert caption below or above
[' ',od.captitle], obj.wd2num(od.cappos))
r.ParagraphFormat.Alignment = align1 ; % caption is aligned with rows
% Create bookmark for the caption
if numel(od.bmn) > 0 % if bookmark name specified
newtab.Range.Select; % select the table range
obj.Select({dir2cap,'wdLine',1,'wdMove'}); % move selection one line up or down
obj.Select({'end','wdLine',1,'wdMove'}); % go to end of this line
obj.Select({'home','wdLine',1,'wdExtend'}); % extend selection to the start of this line
h.ActiveDocument.Bookmarks.Add( ... % create a bookmark for the selection
[od.bmn,'_caption'], ...
h.Selection.Range);
end
end
end % InsertTable
function varargout = InsertFigure (obj,varargin)
% INSERTFIGURE Insert a figure in the document with caption and bookmark
od = struct( ... % defaults for arguments
'what', [], ... % graphics handle or graphics file name
'lineBreaks', [1,1], ... % vector with number of line breaks before and after figure
'bmn', '', ... % bookmark name to associate with figure
'captitle', '', ... % caption to be given to figure
'cappos', 'wdCaptionPositionBelow', ... % position of caption: one of enum WdCaptionPosition
'align', 'wdAlignParagraphCenter', ... % alignment one of enum WdParagraphAlignment
'perc', [], ... % image width as percentage of document width (0-100)
'title', '' , ... % title of figure (in figure properties)
'descr', '' ... % description of figure (in figure properties)
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ; % actxserver handle
for k = 1:od.lineBreaks(1)
h.Selection.TypeParagraph ; % Line breaks before figure
end
% Insert the figure and set properties
if ishandle(od.what) % argument is graphics handle
% filetype = 'jpg' ; % use jpg format
% filename = sprintf('%s.%s', ... % generate temp file name
% tempname,filetype);
% saveas(od.what, filename, filetype) ; % save image to jpg temp file
filetype = 'emf' ; % use jpg format
filename = sprintf('%s.%s', ... % generate temp file name
tempname,filetype);
set(0,'CurrentFigure',od.what)
print(filename,'-dmeta','-r600')
else
filename = od.what ; % use filename as given
end
newfig= h.Selection.InlineShapes. ... % insert the (temporary) graphics file
AddPicture(filename);
if ishandle(od.what)
delete(filename) ; % remove temp file
end
if numel(od.perc) > 0 % when specified
newfig.ScaleHeight = od.perc ; % scale height with the given percentage
newfig.ScaleWidth = od.perc ; % scale width with the given percentage
end
if numel(od.title) > 0
newfig.Title = od.title ; % set title when specified
end
if numel(od.descr) > 0
newfig.AlternativeText = od.descr ; % set description when specified
end
if nargout > 0
varargout{1} = newfig ;
end
obj.SetStyle({obj.normal}); % set current style to 'Normal'
for k = 1:od.lineBreaks(2)
h.Selection.TypeParagraph ; % Line breaks after table
end
egraph = h.Selection.Range ;
egraph.Collapse(obj.wd2num('wdCollapseEnd')); % point after graph area
if numel(od.captitle) > 0
r = newfig.Range ;
switch od.cappos
case 'wdCaptionPositionAbove'
r.Collapse( ... % collapse selection at start
obj.wd2num('wdCollapseStart'));
r.Select
obj.Select({'left','wdCharacter',1,'wdExtend'}) % select figure
h.Selection.InsertCaption('Figure', ... % insert caption
[' ',od.captitle],obj.wd2num(od.cappos)) ;
obj.Select({'home','wdLine',1,'wdExtend'})
h.Selection.ParagraphFormat.Alignment = ... % alignment for caption
obj.wd2num(od.align) ;
case 'wdCaptionPositionBelow'
r.Collapse( ... % collapse selection at end
obj.wd2num('wdCollapseEnd'));
r.Select
h.Selection.InsertCaption('Figure', ... % insert caption
[' ',od.captitle],obj.wd2num(od.cappos)) ;
r.Select()
h.Selection.TypeParagraph ;
h.Selection.ParagraphFormat.Alignment = ... % alignment for caption
obj.wd2num(od.align) ;
obj.Select({'end','wdLine',1,'wdMove'}) % move to the end of caption
obj.Select({'home','wdLine',1,'wdExtend'}); % extend selection to start of caption
end
if numel(od.bmn) > 0
h.ActiveDocument.Bookmarks.Add( ... % bookmark for caption
[od.bmn,'_caption'],h.Selection.Range);
h.ActiveDocument.Bookmarks.Add( ... % bookmark for figure
od.bmn,newfig.Range);
end
newfig.Range.ParagraphFormat.Alignment = ... % alignment for figure
obj.wd2num(od.align) ;
else
if numel(od.bmn) > 0
h.ActiveDocument.Bookmarks.Add(od.bmn,newfig.Range);
end
end
egraph.Select() ; % set selection to last point of graph area
end % InsertFigure
function InsertXRefCaption(obj,varargin)
% INSERTXREFCAPTION Insert cross reference to a caption
od = struct( ... % defaults for arguments
'bmn', '', ... % bookmark name of table, figure, ...
'reftype', 'wdCaptionTable', ... % ReferenceType one of enum WdReferenceKind
'refkind', 'wdOnlyLabelAndNumber', ... % ReferenceKind one of enum WdReferenceKind
'ashyper', true ... % Insert as hyperlink
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ; % actxserver handle
bkmrk = [od.bmn,'_caption'] ; % bookmark to caption of table
cap_text = h.ActiveDocument. ... % caption text
Bookmarks.Item(bkmrk).Range.Text ;
reftype = obj.wd2num(od.reftype) ; % translated reference type
all_captions = ... % all captions of this reftype
h.ActiveDocument. ...
GetCrossReferenceItems(reftype) ;
[~,ix] = ismember(cap_text,all_captions) ; % find seq nr of this caption in all captions
h.Selection.InsertCrossReference( ...
reftype , ... % ReferenceType
obj.wd2num(od.refkind), ... % ReferenceKind
ix, ... % ReferenceItem = sequence number
od.ashyper) ; % insert as hyperlink ?
end % InsertXRefCaption
function SetTableColWidth(obj,varargin)
% SETTABLECOLWIDTH Set column widths for table
od = struct( ... % defaults for arguments
'columns', [] , ... % column number to change ([] is all)
'widths', [], ... % widths in cm or as a percentage
'width_type', 'wdPreferredWidthPoints' ... % width type one of enum WdPreferredWidthType
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ;
if h.Selection.Information('wdWithInTable')
cols = h.Selection.Tables. ... % Columns object for this table
Item(1).Columns ;
nbCols = cols.Count; % number of columns
if numel(od.columns) == 0
columns = 1:nbCols; % columns to change: all
else
columns = od.columns(:)' ; % columns to change: force to row vector
end
if min(columns) < 1 || max(columns) > nbCols
fprintf(['column specification', ... % warning message
' does not match', ...
' number of columns\n']);
return
end
if not(ismember(numel(od.widths), ... % numel(widths) should be 1 or be equal to
[1,numel(columns)])) % number of specified columns
fprintf(['number of elements', ... % warning message
' in width does not match', ...
' number of columns\n']);
return
end
if numel(od.widths) == 1
widths = repmat(od.widths,1, ... % expand a scalar
numel(columns))';
else
widths = od.widths; % copy
end
h.Selection.Tables.Item(1). ... % disallow AutoFit
AllowAutoFit = false ;
for i = columns
cols.Item(i).PreferredWidthType ...
= obj.wd2num(od.width_type) ;
switch od.width_type
case 'wdPreferredWidthAuto'
h.Selection.Tables.Item(1). ... % allow AutoFit
AllowAutoFit = true ;
case 'wdPreferredWidthPoints'
cols.Item(i).PreferredWidth = ... % convert cm to points
widths(i) .* 28.3465;
case 'wdPreferredWidthPercent'
cols.Item(i).PreferredWidth = ... % copy percentage
widths(i) ;
end
end
end
end % SetTableColWidth
function SetTableColAlign(obj,varargin)
% SETTABLECOLALIGN Set alignment for columns for table
od = struct( ... % defaults for arguments
'columns', [] , ... % column numbers to change ([] is all)
'align', [] ... % cell array with WdParagraphAlignment constants
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ;
align1 = obj.wd2num(od.align) ;
if h.Selection.Information('wdWithInTable')
nbCols = h.Selection.Tables.Item(1).Columns.Count;
if numel(od.columns) == 0
columns = 1:nbCols; % columns to change: all
else
columns = od.columns(:)' ; % columns to change: force to row vector
end
if min(columns) < 1 || max(columns) > nbCols
fprintf(['column specification', ... % warning message
' does not match', ...
' number of columns\n']);
return
end
if not(ismember(numel(align1),[1, ...
numel(columns)]))
fprintf('number of elements in align does not match number of columns\n')
return
end
if numel(align1) == 1
align1 = repmat(align1,1, ...
numel(columns))';
end
t = h.Selection.Tables.Item(1) ;
for i = columns
t.Columns.Item(i).Select
h.Selection.ParagraphFormat.Alignment = align1(i) ;
end
t.Select ;
end
end % SetTableColAlign
function SelectTableColumn(obj,varargin)
% SELECTTABLECOLUMN Select a column of a table
od = struct( ... % defaults for arguments
'colnr', 1 ... % number of the column to select
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ;
if h.Selection.Information('wdWithInTable')
nbCols = h.Selection.Tables.Item(1).Columns.Count;
if (od.colnr < 0) || (od.colnr > nbCols)
fprintf('selected column not in table\n')
return
end
h.Selection.Tables.Item(1).Columns.Item(od.colnr).Select;
end
end % SelectTableColumn
function SelectTableRow(obj,varargin)
% SELECTTABLEROW Select a row of a table
od = struct( ... % defaults for arguments
'rownr', 1 ... % number of the row to select
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ;
if h.Selection.Information('wdWithInTable')
nbRows = h.Selection.Tables.Item(1).Rows.Count;
if (od.rownr < 0) || (od.rownr > nbRows)
fprintf('selected row not in table\n')
return
end
h.Selection.Tables.Item(1).Rows.Item(od.rownr).Select;
end
end % SelectTableRow
function SelectTableCell(obj,varargin)
% SELECTTABLECELL Select a cell of a table
od = struct( ... % defaults for arguments
'rownr', 1 , ... % row number of the cell to select
'colnr', 1 ... % column number of the cell to select
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ;
rownr =od.rownr ; colnr = od.colnr ;
if numel(colnr) == 0
colnr = rownr{2} ;
rownr = rownr{1} ;
end
if h.Selection.Information('wdWithInTable')
nbRows = h.Selection.Tables.Item(1).Rows.Count;
nbCols = h.Selection.Tables.Item(1).Columns.Count;
if (rownr < 0) || (rownr > nbRows) || ...
(colnr < 0) || (colnr > nbCols)
fprintf('selected cell not in table\n')
return
end
h.Selection.Tables.Item(1).Cell(rownr,colnr).Select;
end
end % SelectTableCell
function [data,titel, descr] = GetTable(obj,varargin)
% GETTABLE Get data from current table
od = struct( ... % defaults for arguments
'ignoreHeader', true ... % ignore row header ?
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ;
if h.Selection.Information('wdWithInTable') % check cursor is in table
nbRows = h.Selection.Tables(1).Item(1).Rows.Count - od.ignoreHeader; % ignoreHeader = true (1) or false (0)
nbCols = h.Selection.Tables(1).Item(1).Columns.Count;
data = cell(nbRows, nbCols); % preallocate
for col = 1:nbCols
for row = 1:nbRows
cellText = h.Selection.Tables. ...
Item(1).Cell(row+od.ignoreHeader,col). ...
Range.Text;
data{row,col} = cellText(1:end-2); % end-2 -> ignore line break
end
end
descr = h.Selection.Tables.Item(1).Descr;
titel = h.Selection.Tables.Item(1).Title;
end
end % GetTable
function WriteTable(obj,varargin)
% WRITETABLE Write data to current table
od = struct( ... % defaults for arguments
'data', [] , ... % (character) data to write to table
'fstRow', 1 , ... % number of the first row to write to
'fstCol', 1 ... % number of the first column to write to
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ;
if h.Selection.Information('wdWithInTable') % check cursor is in table
autofit = h.Selection.Tables.Item(1).AllowAutoFit;
if autofit % turn off AutoFit for a faster writing
h.Selection.Tables.Item(1).AllowAutoFit = false;
end
[dt_ndRows, dt_nbCols] = size(od.data);
tbl_nbRows = h.Selection.Tables.Item(1).Rows.Count;
tbl_nbCols = h.Selection.Tables.Item(1).Columns.Count;
nbCols = min(dt_nbCols, tbl_nbCols-od.fstCol+1);
ndRows = min(dt_ndRows, tbl_nbRows-od.fstRow+1);
for col = 1:nbCols
for row = 1:ndRows
h.Selection.Tables.Item(1). ...
Cell(row+od.fstRow-1,col+od.fstCol-1).Range.Text = od.data{row,col};
end
end
h.Selection.Tables.Item(1).AllowAutoFit = autofit;
end
end % WriteTable
function SetRowNumb(obj,varargin)
% SETROWNUMB Change number of rows in current table
od = struct( ... % defaults for arguments
'nbRows', 1 ... % set number of rows to nbRows
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ;
tbl_nbRows = h.Selection.Tables.Item(1).Rows.Count;
row_diff = od.nbRows - tbl_nbRows;
if ~(row_diff==0) % increase or decrease
if row_diff>0 % add rows
for i=1:row_diff
h.Selection.Tables.Item(1).Rows.Add;
end
else % remove rows
for i=1:(-row_diff)
h.Selection.Tables.Item(1).Rows.Last.Delete;
end
end
end
end % SetRowNumb
function SetColumnNumb(obj,varargin)
% SETCOLUMNNUMB Change number of cols in current table
od = struct( ... % defaults for arguments
'nbCols', 1 ... % set number of columns to nbCols
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ;
tbl_nbCols = h.Selection.Tables.Item(1).Columns.Count;
col_diff = od.nbCols - tbl_nbCols;
if ~(col_diff==0) % increase or decrease
if col_diff>0 % add cols
for i=1:col_diff
h.Selection.Tables.Item(1).Columns.Add;
end
else % remove cols
for i=1:(-col_diff)
h.Selection.Tables.Item(1).Columns.Last.Delete;
end
end
end
end % SetColumnNumb
function SetStyle(obj,varargin)
% SETSTYLE Set current text style, used later by SelectionInsertText
od = struct( ... % defaults for arguments
'style', obj.normal ... % style to use
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
obj.currentStyle = od.style;
end % SetStyle
function SelectionInsertBreak(obj,varargin)
% SELECTIONINSERTBREAK Insert a break of specified type at start of selection
od = struct( ... % defaults for arguments
'breaktype', 'wdPageBreak' ... % one of enum WdBreakType
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ;
breaktype = obj.wd2num(od.breaktype) ; % translate constant
h.Selection.HomeKey; % goto start of selection
h.Selection.InsertBreak(breaktype) ; % insert the break of specified type replacing the selection
h.Selection.MoveDown ; % moves the selection one wdLine down
end % SelectionInsertBreak
function returnV = Goto(obj,varargin)
% GOTO Jump to specified location in document
od = struct( ... % defaults for arguments
'what', 'wdGotoBookmark' , ... % one of enum enum WdGoToItem
'which', 'wdGotoAbsolute' , ... % one of enum WdGoToDirection
'count', 1 , ... % number of 'what'
'name', '' , ... % name of 'what'
'delete', false ... % delete contents indicated selection
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ;
which = obj.wd2num(od.which) ; % translate WdGoToDirection
what = obj.wd2num(od.what) ; % translate WdGoToItem
if what == -1
which = [] ; count = [] ; % ?? otherwise bookmark is not found
end
returnV = h.Selection.GoTo(what, which, count, od.name);
if od.delete
h.Selection.Delete;
end
end % Goto
function found = FindText(obj, varargin)
% FINDTEXT Find text in document
od = struct( ... % defaults for arguments
'textToFind', '' , ... % text to find
'forward', true , ... % forward (true) or backward (false)
'replacement', '' , ... % replacement text
'find_opts', struct() ... % find options
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
h = obj.w ;
defopts = struct( ... % options for Find.Execute
'wdReplace', 'wdReplaceNone' , ... % replacement options
'wdFindwrap', 'wdFindContinue' , ... % WdFindWrap options
'MatchCase', false , ...
'MatchWholeWord', false , ...
'MatchWildcards', false , ...
'MatchSoundsLike', false , ...
'MatchAllWordForms', false , ...
'Format', false ) ;
opts = wordserver.fn_copy_options( ... % merge extra options with default ones
defopts, od.find_opts);
wdrepcode = obj.wd2num(opts.wdReplace) ;
wdfwcode = obj.wd2num(opts.wdFindwrap) ;
h.Selection.Find.ClearFormatting;
h.Selection.Find.Replacement.ClearFormatting
found = h.selection.Find.Execute( ...
od.textToFind, opts.MatchCase, ...
opts.MatchWholeWord, opts.MatchWildcards, ...
opts.MatchSoundsLike, opts.MatchAllWordForms, ...
od.forward, wdfwcode, ...
opts.Format, od.replacement, wdrepcode) ;
end % FindText
function Select(obj,varargin)
% SELECT Extend or move selection 'right', 'left', 'home' or 'end' , 'up' or 'down'
od = struct( ... % defaults for arguments
'direction', 'right' , ... % direction ('right', 'left', 'home' or 'end' , 'up', 'down'
'unit', 'wdCharacter' , ... % unit one of enum WdUnits
'count', 1 , ... % number of 'units'
'extend', 'wdMove' ... % 'wdMove' or 'wdExtend'
);
od =wordserver.get_options(od,varargin{:}); % merge arguments with defaults
unit = obj.wd2num(od.unit) ;
extend = obj.wd2num(od.extend) ;
switch lower(od.direction)
case 'left'
obj.w.Selection.MoveLeft(unit, od.count, extend);
case 'right'
obj.w.Selection.MoveRight(unit, od.count, extend);
case 'up'
obj.w.Selection.MoveUp(unit, od.count, extend);
case 'down'
obj.w.Selection.MoveDown(unit, od.count, extend);
case 'home'
if ismember(unit,[5 6 9 10])
obj.w.Selection.HomeKey(unit, extend);
end
case 'end'
if ismember(unit,[5 6 9 10])
obj.w.Selection.EndKey(unit, extend);
end
end
end % Select
function CreateTOC(obj,varargin)
% CREATETOC Create the table of contents, list of figures or list of tables
od = struct( ... % defaults for arguments
'type', 'TOC' , ... % type TOC, Figure or Table
'text', 'Table of Contents' , ... % text to print above TOC or list
'fontstruct', [] , ... % struct for use in SelectionSetFont to print text
'tableader', 'wdTabLeaderDots', ... % enum WdTabLeader
'include_label', true, ... % include label in list of figure or table
'UseHeadingStyles', true, ... % forced to false for Figure and Table
'UpperHeadingLevel', 1, ... % highest level to include in TOC