Export data from datatable with select element exports each option from the select element

时光毁灭记忆、已成空白 提交于 2019-11-30 14:25:40

Use exportOptions'format.body callback to get control over the exported data. Use the dataTables API to find the current selected value for each <select> box. Here for the first column and pdf :

buttons: [
  { 
    extend : 'pdf',
    exportOptions : {
      format: {
        body: function( data, row, col, node ) {
          if (col == 0) {
            return table
              .cell( {row: row, column: col} )
              .nodes()
              .to$()
              .find(':selected')
              .text()
           } else {
              return data;
           }
        }
      }
    },
    ...
  }
]

Where table is the table instance, in your case me.dataTable_obj. Now just change if (col == 0) { so it respond to the columns where you have <select> boxes (I dont know that).

Mikhail Ushakov

In case you'll use export format for only visible columns, fixed column indexes will play some tricks on you, so what helped in my case was checking the node child and if it is select, then make the format

body: function(data, row, col,node) {
   var elementType = node.firstChild;
   if (elementType != null) {
         if (elementType.nodeName == "SELECT") return 
         $(elementType).find(':selected').text();
         else return data;
   }
   else return data

Credit to Mikhail Ushakov for getting me started. There were some opportunities to simplify the code and to make it work a little smoother (in my case) the biggest problem being that just about everything in my tables is a link or select. In the case of links, the other code was also capturing the html for the link, not the text. In my case I also had weird stuff like tables, so I had to anticipate multiple children in each node. Also opted not to use JQuery ;)

exportOptions: {
    format   : {
        body : (data, row, col, node) => {
            let node_text = '';
            const spacer = node.childNodes.length > 1 ? ' ' : '';
            node.childNodes.forEach(child_node => {
                const temp_text = child_node.nodeName == "SELECT" ? child_node.selectedOptions[0].textContent : child_node.textContent;
                node_text += temp_text ? `${temp_text}${spacer}` : '';
            });
            return node_text;
        }
    }
},
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!