You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在DataTables导出的Excel中合并首行并居中标题

DataTables Excel导出:首行合并+标题居中实现方案

针对使用DataTables的excelHtml5导出时,首行未合并、标题左对齐的问题,直接修改customize函数即可实现需求,完整代码如下:

{
  extend: 'excelHtml5',
  footer: true,
  text: 'Save as Excel',
  pageSize: 'A4',
  title:'',
  filename:'shop',
  messageTop: 'shop',
  
  customize: function (xlsx) {
    var sheet = xlsx.xl.worksheets['sheet1.xml'];

    // --- 新增:处理首行合并与居中 ---
    var firstRow = $('row:first', sheet);
    var firstCell = $('c:first', firstRow);
    // 合并所有列:表格共9列,mergeAcross设为8(从当前列向后合并8列,总计9列)
    firstCell.attr('mergeAcross', 8);
    // 删除首行多余单元格,避免Excel格式异常
    $('c:not(:first)', firstRow).remove();
    // 给首行标题添加水平+垂直居中对齐
    var alignment = document.createElementNS('http://schemas.openxmlformats.org/spreadsheetml/2006/main', 'alignment');
    alignment.setAttribute('horizontal', 'center');
    alignment.setAttribute('vertical', 'center');
    alignment.setAttribute('wrapText', '1');
    firstCell[0].appendChild(alignment);
    // --- 首行处理结束 ---

    // 原有样式设置:首行加粗
    $('row:first c', sheet).attr('s', '2'); 
    // A列所有行加粗
    $('row c[r^="A"]', sheet).attr('s', '2');
    // B列样式(保留原有设置)
    $('row c[r^="B"]', sheet).attr('s', '55');
    // 第二行(表头)加粗
    $('row[r=2] c', sheet).attr('s', '2');

    // 列宽设置(保留原有)
    var col = $('col', sheet);
    $(col[0]).attr('width', 8);
    $(col[1]).attr('width', 25);
    $(col[2]).attr('width', 8);
    $(col[3]).attr('width', 9);
    $(col[4]).attr('width', 7);
    $(col[5]).attr('width', 6);
    $(col[6]).attr('width', 7);
    $(col[7]).attr('width', 8);
    $(col[8]).attr('width', 8);
    
    // 行高设置(保留原有)
    $('row', sheet).each(function (index) {
      if (index > 0) {
        $(this).attr('ht', 32);
        $(this).attr('customHeight', 1);
      }
    });
  }
}

关键修改说明:

  1. 首行合并:给首行第一个单元格添加mergeAcross属性,值为总列数减1(表格共9列,所以设为8),同时删除首行其他多余单元格,避免Excel解析冲突。
  2. 标题居中:手动创建Excel的alignment节点,设置水平、垂直居中,同时保留原有加粗样式(s=2)。
  3. 原有列宽、行高、其他样式设置均保留,不影响原有导出效果。

内容的提问来源于stack exchange,提问作者gopal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 18:09:19