允许添加表格,然后操作表格,这样只要操作表格内的数据即可,而且附带更多功能。个人推荐使用。
添加表格
// 将表格添加到工作表
worksheet.addTable({
name: 'MyTable', //表格名称
ref: 'A2', //表格的左上方单元格
headerRow: true, //在表格顶部显示标题,选填,默认是true
totalsRow: true, //在表格底部显示总计,选填,默认是false
style: { //额外的样式属性,选填,见下
theme: 'TableStyleDark3',
showRowStripes: true,
},
columns: [ //定义列字段,见下
{name: 'id', totalsRowLabel: '合计:', filterButton: true},
{name: '数值', totalsRowFunction: 'sum'},
],
rows: [ //行数据
[1, 70.10],
[2, 70.60],
[3, 70.10],
],
});
表格属性
额外的样式 style:
样式属性 | 描述 | 是否必填 | 默认值 | 说明 |
---|---|---|---|---|
theme | 桌子的颜色主题 | N | 'TableStyleMedium2' |
格式是:TableStyle[Shade][Number], Shades(阴影),Number(数字)可以是以下之一: Light, 1-21 Medium, 1-28 Dark, 1-11 |
showFirstColumn | 突出显示第一列(粗体) | N | false |
|
showLastColumn | 突出显示最后一列(粗体) | N | false |
|
showRowStripes | 用交替的背景色显示行 | N | false |
|
showColumnStripes | 用交替的背景色显示列 | N | false |
定义列字段 columns:
| 列属性 | 描述 | 是否必填 | 默认值 | 说明 |
| name | 列名,也用在标题中 | Y | | |
| —- | —- | —- | —- | —- |
| filterButton | 切换标题中的过滤器控件 | N | false | |
| totalsRowLabel | 用于描述统计行的标签(第一列) | N | 'Total'
| |
| totalsRowFunction | 统计函数名称 | N | 'none'
| 名称见下 |
| totalsRowFormula | 自定义函数的可选公式 | N | | |
totalsRowFunction 统计函数名称:
统计函数 | 描述 |
---|---|
none | 此列没有统计函数 |
average | 计算列的平均值 |
countNums | 统计数字条目数 |
count | 条目数 |
max | 此列中的最大值 |
min | 此列中的最小值 |
stdDev | 该列的标准偏差 |
var | 此列的方差 |
sum | 此列的条目总数 |
custom | 自定义公式。 需要关联的 totalsRowFormula 值。 |
获取表格
const table = worksheet.getTable('MyTable');
修改表格属性
const table = worksheet.getTable('MyTable');
table.属性 = 修改后的值;
// 将表更改提交到工作表中
//由于这些操作中的许多操作可能会对工作表产生副作用,因此更改必须在完成后立即提交。
table.commit();
添加/删除列
const table = worksheet.getTable('MyTable');
table.removeColumns(1, 1);// 删除第二列
// 在索引 1 处插入新列(包含数据)
table.addColumn(
{name: 'Letter', totalsRowFunction: 'custom', totalsRowFormula: 'ROW()', totalsRowResult: 6, filterButton: true},
['a', 'b', 'c', 'd'],
2
);
// 将表更改提交到工作表中
//由于这些操作中的许多操作可能会对工作表产生副作用,因此更改必须在完成后立即提交。
table.commit();
列属性
const table = worksheet.getTable('MyTable');
// 获取第二列的列包装器
const column = table.getColumn(1);
// 设置一些属性
column.name = 'Code';
column.filterButton = true;
column.style = {font:{bold: true, name: 'Comic Sans MS'}};
column.totalsRowLabel = 'Totals';
column.totalsRowFunction = 'custom';
column.totalsRowFormula = 'ROW()';
column.totalsRowResult = 10;
// 将表更改提交到工作表中
//由于这些操作中的许多操作可能会对工作表产生副作用,因此更改必须在完成后立即提交。
table.commit();
添加/删除行
const table = worksheet.getTable('MyTable'); //获取表格
table.removeRows(0, 2);// 删除前两行
table.addRow([4,86], 5); // 在索引 5 处插入新行
table.addRow([7,90]); //在表格底部追加新行
// 将表更改提交到工作表中
//由于这些操作中的许多操作可能会对工作表产生副作用,因此更改必须在完成后立即提交。
table.commit();