运行代码效果如下
首先创建一个新的word文档,并新建5个样式。
word = actxserver('Word.Application');
document = word.Documents.Add;
word.Visible = 1;
selection = word.Selection;
% 新建样式
title1_style = document.Styles.Add('MyNewStyle',1);
title2_style = document.Styles.Add('MyNewStyle1',1);
title3_style = document.Styles.Add('MyNewStyle2',1);
content_style = document.Styles.Add('MyNewStyle3',1);
figure_style = document.Styles.Add('MyNewStyle4',1);
新建列表,注意将单级列表转换为多级列表。
listTemplate = document.ListTemplates.Add();
listTemplate.Convert(1);
访问并修改列表中每一级别的设置和链接样式。这样后面套用这些新样式的时候就会自动编号啦~
% 访问第一级别的设置
listLevel = listTemplate.ListLevels.Item(1);
% 修改第一级别的设置
listLevel.NumberFormat = '%1';
listLevel.NumberStyle = 'wdListNumberStyleArabic';
listLevel.LinkedStyle = 'MyNewStyle';
% 访问修改第二级别的设置
listLevel = listTemplate.ListLevels.Item(2);
listLevel.NumberFormat = '%1.%2';
listLevel.NumberStyle = 'wdListNumberStyleArabic';
listLevel.LinkedStyle = 'MyNewStyle1';
% 访问修改第三级别的设置
listLevel = listTemplate.ListLevels.Item(3);
listLevel.NumberFormat = '%1.%2.%3';
listLevel.NumberStyle = 'wdListNumberStyleArabic';
listLevel.LinkedStyle = 'MyNewStyle2';
要让这些新建的样式显示在word文档的导航条中,需要修改这些样式的大纲级别,因为默认的级别是“正文文本”,不会显示在导航条中。修改为1级/2级/3级意味着导航条中文字的缩进不同。
% 更改样式格式
selection.Start = selection.end;selection.TypeParagraph;
selection.Text = '标题1';
selection.Style = title1_style;
selection.Style.Font.Name = '宋体';
selection.Style.Font.Name = 'Time New Roman';
selection.Style.Font.Size = 15;
selection.Style.Font.Bold = 0;
selection.Style.ParagraphFormat.LineSpacingRule = 'wdLineSpace1pt5';
selection.Style.ParagraphFormat.Alignment = 'wdAlignParagraphCenter';
selection.Style.ParagraphFormat.OutlineLevel = 'wdOutlineLevel1'; %设定为大纲级别1
selection.Start = selection.end;selection.TypeParagraph;
selection.Style = title2_style;
selection.Text = '标题2';
selection.Style.Font.Name = '宋体';
selection.Style.Font.Name = 'Time New Roman';
selection.Style.Font.Size = 12;
selection.Style.Font.Bold = 0;
selection.Style.ParagraphFormat.LineSpacingRule = 'wdLineSpace1pt5';
selection.Style.ParagraphFormat.Alignment = 'wdAlignParagraphLeft';
selection.Style.ParagraphFormat.OutlineLevel = 'wdOutlineLevel2'; %设定为大纲级别2
selection.Start = selection.end;selection.TypeParagraph;
selection.Style = title3_style;
selection.Text = '标题3';
selection.Style.Font.Name = '宋体';
selection.Style.Font.Name = 'Time New Roman';
selection.Style.Font.Size = 12;
selection.Style.Font.Bold = 0;
selection.Style.ParagraphFormat.LineSpacingRule = 'wdLineSpace1pt5';
selection.Style.ParagraphFormat.Alignment = 'wdAlignParagraphLeft';