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

  • 6
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值