我是靠谱客的博主 爱笑乌冬面,最近开发中收集的这篇文章主要介绍Matlab写Word文档,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

本文简述如何用Matlab编写脚本写Word文档,具体方法是调用Word Server,用其提供的接口写Word文档。使用此方法时用户不应与Word程序图形界面交互,例如用鼠标点Word程序某个位置会使得写入的内容从光标处插入。先看示例代码

clear;
%start the server
try
Word = actxGetRunningServer('Word.Application');
catch
Word = actxserver('Word.Application');
end
Word.Visible = 1;
%New document
Doc = Word.Documents.Add;
%write
Word.Selection.Start = 0;
Word.Selection.Text = "1";
Word.Selection.Start = Word.Selection.End;
Word.Selection.TypeParagraph;
Word.Selection.Text = "2";
Word.Selection.Start = Word.Selection.End;
%insert a table
Table = Doc.Tables.Add(Word.Selection.Range,10,10);
Table.Borders.InsideLineStyle = 'wdLineStyleSingle';
Table.Borders.OutsideLineStyle = 'wdLineStyleSingle';
Table.Cell(1,1).Range.Text = "1,1";
Table.Cell(2,2).Range.Text = "2,2";
Word.Selection.Start = Doc.Content.End;
%write after the table
Word.Selection.Text = "3";
Word.Selection.Start = Word.Selection.End;
%insert a picture
Word.Selection.TypeParagraph;
handle = Doc.InlineShapes.AddPicture("C:pic1.png");
Word.Selection.Start = Doc.Content.End;
%write after picture
Word.Selection.Text = "4";
Word.Selection.Start = Word.Selection.End;

注意有多个字符串分开输出时,需要令Word.Selection.Start = Word.Selection.End 或 Word.Selection.Start = Doc.Content.End. 否则Start不会变化,再写字符串会覆盖之前的内容。到底用哪个End,取决于上1个操作用的是Word还是Doc. 比如插图是Doc的操作,就用Word.Selection.Start = Doc.Content.End.

表格的行、列编号都从1开始。

把一些功能封装成函数,如下

function write_title(Word, title, num)
Word.Selection.Text = title;
Word.Selection.Style = sprintf('标题 %d',num);
Word.Selection.Font.ColorIndex = 1; %black
Word.Selection.Start = Word.Selection.End;
write_newline(Word);
end
function Table = NewTable(Word, Doc, Row_Num, Column_Num, Column_Names)
Word.Selection.TypeParagraph;
Word.Selection.Start = Word.Selection.End;
Table = Doc.Tables.Add(Word.Selection.Range,Row_Num, Column_Num);
Table.Borders.InsideLineStyle = 'wdLineStyleSingle';
Table.Borders.OutsideLineStyle = 'wdLineStyleSingle';
for i = 1: Column_Num
Table.Cell(1,i).Range.Text = Column_Names{1,i};
end
Word.Selection.Start = Doc.Content.End;
Word.Selection.TypeParagraph;
Word.Selection.Start = Word.Selection.End;
end

最后

以上就是爱笑乌冬面为你收集整理的Matlab写Word文档的全部内容,希望文章能够帮你解决Matlab写Word文档所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(49)

评论列表共有 0 条评论

立即
投稿
返回
顶部