主要内容

本页采用了机器翻译。点击此处可查看英文原文。

格式化表列

此示例说明如何对报告中的表列应用格式设置。您将创建一个表,导入数据,并用数据填充表条目。您以编程方式通过应用表样式来格式化整个表。然后,通过应用粗体和颜色格式样式来格式化表中的列,并按列指定表条目中内容的对齐方式。

创建文档并导入数据

导入文档对象模型 (DOM) 命名空间。创建一个 HTML 文档 FormatColumns

import mlreportgen.dom.*
doc = Document("FormatColumns","html");

将示例数据集 outages.csv 作为表导入。

outages = readtable("outages.csv","TextType","string");

创建表并设置格式

创建一个正式表和一个用于表头的表行。

table = FormalTable;
header = TableRow;

为来自 outages 表的变量名向表头中添加条目。对表头行应用粗体格式和 14pt 字体,然后将该行追加到表中。

for colNum = 1:width(outages)
    append(header,TableEntry(outages.Properties.VariableNames{colNum}));
end
header.Style = {Bold(true),FontSize("14pt")};
appendHeaderRow(table,header);

对于 outages 表的前 15 行,创建表行并将该行追加到 table

for rowNum = 1:15
    row=TableRow;
    for colNum = 1:width(outages)
        entry = Text(outages{rowNum,colNum});
        append(row,TableEntry(entry));
    end
    append(table,row);
end 

定义一个表样式,为行和列添加边框和分隔符。将文本设置为 12pt 字体。

table.Style = {Border("solid"),RowSep("solid"),...
    ColSep("solid"),FontSize("12pt"),...
    ResizeToFitContents(true)};

格式化表列

创建一个跨六列的 TableColSpecGroup 对象。

specGroup = TableColSpecGroup;
specGroup.Span = 6;

要格式化表中的第一列,请创建一个 TableColSpec 对象。将背景颜色设置为浅蓝色。

spec(1) = TableColSpec;
spec(1).Span = 2;
spec(1).Style = {BackgroundColor("lightblue")};

要格式化接下来的四列,请创建一个跨四列的 TableColSpec 对象。将水平对齐方式设置为居中。

spec(2) = TableColSpec;
spec(2).Span = 3;
spec(2).Style = {HAlign("center")};

要格式化表中的最后一列,请创建一个 TableColSpec 对象。对表条目应用粗体格式并将背景颜色设置为薰衣草色。

spec(3) = TableColSpec;
spec(3).Span = 1;
spec(3).Style = {Bold(true), BackgroundColor("lavender")};

specGroup.ColSpecs = spec;
table.ColSpecGroups = specGroup;

将表追加到报告。然后,查看报告。

append(doc,table);
close(doc);
rptview(doc);

Table with the imported data. The first two columns have a light blue background color, the content in the next three columns is centered, and the last column has bold text and a lavender background color.

另请参阅

| |

主题