Export value with Linebreaks into single cell in Excel. jQuery Datatables

烂漫一生 提交于 2019-12-05 03:45:19

Let's have a complete example.

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">

  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/tabletools/2.2.4/css/dataTables.tableTools.css">

  <script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
  <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/tabletools/2.2.4/js/dataTables.tableTools.min.js"></script>

  <script type="text/javascript" language="javascript" class="init">
   $(document).ready(function() {
    $('#papercliptable').DataTable( {
     dom: 'T<"clear">lfrtip',

     tableTools: {
      "sSwfPath": "/copy_csv_xls_pdf.swf",
      "aButtons": [{
       "sExtends": "xls",
       "sFileName": "test.csv",
       "fnCellRender": function (sValue, iColumn, nTr, iDataIndex) {
         console.log("sValue = " + sValue);
         console.log("iColumn = " + iColumn);
         re = /<br\s*\/?>/i;
         if (re.test(sValue)) {
          return '"' + sValue.replace(/<br\s*\/?>/ig, "\n") + '"';
         } else {
          return sValue;
         }
        }
      }]
     }
    });
   });
  </script>

</head>

<body>
<table id="papercliptable">
 <thead>
  <tr>
   <th>A</th>
   <th>B</th>
   <th>C</th>
   <th>D</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>12345</td>
   <td>Value1</td>
   <td>Value2</td>
   <td>This<br/>is<br/>a<br/>test.</td>
  </tr>
 </tbody>
</table>
</body>
</html>

Note, you have to have the copy_csv_xls_pdf.swf within your own domain. You can download it from: https://cdn.datatables.net/tabletools/2.2.4/

This works for me and produces:

CSV:

A   B   C   D
12345   Value1  Value2  "This
is
a
test."

Note, the spaces between the columns are horizontal tabs "\t" 0x09.

Excel:

Note, this is the result in Excel if the *.csv is opened via File - Open. The Text Import Wizard can't handle line breaks within cells in correct manner.

If the content contains new line characters you need to delimit it within double quotes. So use

return '"' + sValue.replace(/<br\s*\/?>/ig, "\r\n") + '"';

Of course you need to do this only if the content contains \r\n (otherwise numbers get formatted as text)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!