允许添加表格,然后操作表格,这样只要操作表格内的数据即可,而且附带更多功能。个人推荐使用。

添加表格

  1. // 将表格添加到工作表
  2. worksheet.addTable({
  3. name: 'MyTable', //表格名称
  4. ref: 'A2', //表格的左上方单元格
  5. headerRow: true, //在表格顶部显示标题,选填,默认是true
  6. totalsRow: true, //在表格底部显示总计,选填,默认是false
  7. style: { //额外的样式属性,选填,见下
  8. theme: 'TableStyleDark3',
  9. showRowStripes: true,
  10. },
  11. columns: [ //定义列字段,见下
  12. {name: 'id', totalsRowLabel: '合计:', filterButton: true},
  13. {name: '数值', totalsRowFunction: 'sum'},
  14. ],
  15. rows: [ //行数据
  16. [1, 70.10],
  17. [2, 70.60],
  18. [3, 70.10],
  19. ],
  20. });

表格属性

额外的样式 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 值。

获取表格

  1. const table = worksheet.getTable('MyTable');

修改表格属性

  1. const table = worksheet.getTable('MyTable');
  2. table.属性 = 修改后的值;
  3. // 将表更改提交到工作表中
  4. //由于这些操作中的许多操作可能会对工作表产生副作用,因此更改必须在完成后立即提交。
  5. table.commit();

添加/删除列

  1. const table = worksheet.getTable('MyTable');
  2. table.removeColumns(1, 1);// 删除第二列
  3. // 在索引 1 处插入新列(包含数据)
  4. table.addColumn(
  5. {name: 'Letter', totalsRowFunction: 'custom', totalsRowFormula: 'ROW()', totalsRowResult: 6, filterButton: true},
  6. ['a', 'b', 'c', 'd'],
  7. 2
  8. );
  9. // 将表更改提交到工作表中
  10. //由于这些操作中的许多操作可能会对工作表产生副作用,因此更改必须在完成后立即提交。
  11. table.commit();

列属性

  1. const table = worksheet.getTable('MyTable');
  2. // 获取第二列的列包装器
  3. const column = table.getColumn(1);
  4. // 设置一些属性
  5. column.name = 'Code';
  6. column.filterButton = true;
  7. column.style = {font:{bold: true, name: 'Comic Sans MS'}};
  8. column.totalsRowLabel = 'Totals';
  9. column.totalsRowFunction = 'custom';
  10. column.totalsRowFormula = 'ROW()';
  11. column.totalsRowResult = 10;
  12. // 将表更改提交到工作表中
  13. //由于这些操作中的许多操作可能会对工作表产生副作用,因此更改必须在完成后立即提交。
  14. table.commit();

添加/删除行

  1. const table = worksheet.getTable('MyTable'); //获取表格
  2. table.removeRows(0, 2);// 删除前两行
  3. table.addRow([4,86], 5); // 在索引 5 处插入新行
  4. table.addRow([7,90]); //在表格底部追加新行
  5. // 将表更改提交到工作表中
  6. //由于这些操作中的许多操作可能会对工作表产生副作用,因此更改必须在完成后立即提交。
  7. table.commit();