how to use .COM command to insert table/figure to specific location in Words?

5 views (last 30 days)
Hi, I have a word template and I would like to insert the matlab table to my word template at a few specific location. Is there a way to place a marker in the word document and let matlab read the marker location then insert the table there? Thanks.

Answers (2)

UDAYA PEDDIRAJU
UDAYA PEDDIRAJU on 29 Aug 2024
Hi Xiwen,
Use bookmarks in Word to mark locations, then use MATLAB's "actxserver" to interact with Word and insert tables at those bookmarks.

Shubham
Shubham on 30 Aug 2024
Hi Xiwen,
You can interact with the Word document using MATLAB by leveraging the ActiveX server for Word. To insert a table/figure at specific locations, you can add bookmarks in your Word template to mark the specific locations where you want the table or figure to be inserted. Here's how you can do it:
  1. Open you Word document and insert a bookmark with unique name where you want to insert the table/figure.
  2. Use MATLAB's COM Interface to insert a table or a figure. Here's the MATLAB script to insert a table in Word document:
% Start Word and open document
wordApp = actxserver('Word.Application');
doc = wordApp.Documents.Open('C:\path\to\your\template.docx');
% Define table data
data = rand(5, 3);
tableData = array2table(data);
% Find the bookmark where the table should be inserted
bookmark = doc.Bookmarks.Item('bookmark_name');
range = bookmark.Range;
% Create a temporary text file to save the table
tempTableFile = [tempname '.txt'];
writetable(tableData, tempTableFile, 'Delimiter', '\t');
range.InsertFile(tempTableFile);
delete(tempTableFile);
% Save and close
doc.SaveAs2('C:\path\to\save\newDocument.docx');
doc.Close();
wordApp.Quit();
To insert a figure, use a similar approach. Here's how you can do it:
% Save figure
figure; plot(rand(5, 1));
saveas(gcf, 'C:\path\to\figure.png');
% Insert figure
figureBookmark = doc.Bookmarks.Item('FigureLocation1');
figureRange = figureBookmark.Range;
figureRange.InlineShapes.AddPicture('C:\path\to\figure.png');
Refer to the following documentation link for more information on "actxserver":
Hope this helps.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!