将数据表导出到具有橙色背景的Excel

时间:2019-06-25 08:25:48

标签: jquery datatables

我有以下代码段,根据单元格的内容,红色和绿色背景可以显示在F列上

我的问题是,我将如何去做,这样我也可以拥有橙色背景?

buttons: [{
  extend: 'excel',
  text: 'Save as Excel',
  customize: function(xlsx) {
    var sheet = xlsx.xl.worksheets['sheet1.xml'];
    $('row c[r^="F"]', sheet).each(function() {
      if ($('is t', this).text().toUpperCase() == 'Very aware'.toUpperCase() || $('is t', this).text().toUpperCase() == 'Reasonably aware'.toUpperCase()) {
        $(this).attr('s', '15');
      } else if ($('is t', this).text().toUpperCase() == 'Slightly aware'.toUpperCase()) {
        $(this).attr('s', '10');
      } else if ($('is t', this).text().toUpperCase() == 'Unaware'.toUpperCase()) {
        $(this).attr('s', '10');
      } else {

      }
    });
  }
}]

1 个答案:

答案 0 :(得分:1)

由于数据表的内置样式仅包括灰色#D9D9D9,红色#D99795,绿色#C6EfCE和蓝色#C6CFEF背景的选项,因此您必须添加样式您需要自己。

数据表将内置样式存储在属性excelStrings下名为xl/styles.xml的对象中。参见:Buttons/js/buttons.html5.js @ Line:582

您可以通过扩展/自定义excel按钮来添加自定义样式,如下所示:

{
  extend: 'excel',
  text: 'Save as Excel',
  customize: function(xlsx) {
    let sheet = xlsx.xl.worksheets['sheet1.xml'];

    let styles = xlsx.xl['styles.xml']; // Get current styles

    let last_fills_index = $('cellXfs fills', styles).length - 1;
    let last_xf_index = $('cellXfs xf', styles).length - 1;

    let fill_orange = '<fill><patternFill patternType="solid"><fgColor rgb="ffffb024" /><bgColor indexed="64" /></patternFill></fill>';
    let style_fill_orange = '<xf numFmtId="0" fontId="4" fillId="' + (last_fills_index + 1) + '" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>';

    styles.childNodes[0].childNodes[2].innerHTML += fill_orange; // childNodes[2] -> fills
    styles.childNodes[0].childNodes[5].innerHTML += style_fill_orange; // childNodes[5] -> cell xfs

    let sOrangeBackground = last_xf_index + 1;

    $('row c[r^="F"]', sheet).each(function() {
      if ($('is t', this).text().toUpperCase() == 'Very aware'.toUpperCase() || $('is t', this).text().toUpperCase() == 'Reasonably aware'.toUpperCase()) {
        $(this).attr('s', '15');
      } else if ($('is t', this).text().toUpperCase() == 'Slightly aware'.toUpperCase()) {
        $(this).attr('s', sOrangeBackground);
      } else if ($('is t', this).text().toUpperCase() == 'Unaware'.toUpperCase()) {
        $(this).attr('s', '10');
      }
    });
  }
}