2016年4月8日 星期五

備忘~JavaScript export Table to CSV File

中文處理上透過encodeURIComponent()編碼成UTF 8,直接用EXCEL開啟時若中文是亂碼那先檢查(可用NotePad++或UltraEdit之類編輯器檢視)檔案格式是否為 UTF-8 ( 有 BOM )

用PHPExcel()來匯出效果更好寫,不過在部分情況下不允許就將就著用。

1. JavaScript區塊
<script type="text/javascript">
function exportTableToCSV($table, filename) {
var $headers = $table.find('tr:has(th)')
,$rows = $table.find('tr:has(td)')

// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
,tmpColDelim = String.fromCharCode(11) // vertical tab character
,tmpRowDelim = String.fromCharCode(0) // null character

// actual delimiter characters for CSV format
,colDelim = '","'
,rowDelim = '"\r\n"';

// Grab text from table into CSV formatted string
var csv = '"';
csv += formatRows($headers.map(grabRow));
csv += rowDelim;
csv += formatRows($rows.map(grabRow)) + '"';

// 若欲輸出的檔案為 UTF-8 ( 無 BOM )
var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

// 若欲輸出的檔案為 UTF-8 ( 有 BOM )
var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent('\uFEFF' + csv);

$(this)
.attr({
'download': filename
,'href': csvData
//,'target' : '_blank' //if you want it to open in a new window
});

//------------------------------------------------------------
// Helper Functions
//------------------------------------------------------------
// Format the output so it has the appropriate delimiters
function formatRows(rows){
return rows.get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim);
}
// Grab and format a row from the table
function grabRow(i,row){

var $row = $(row);
//for some reason $cols = $row.find('td') || $row.find('th') won't work...
var $cols = $row.find('td');
if(!$cols.length) $cols = $row.find('th');

return $cols.map(grabCol)
.get().join(tmpColDelim);
}
// Grab and format a column from the table
function grabCol(j,col){
var $col = $(col),
$text = $col.text();

return $text.replace('"', '""'); // escape double quotes

}
}
 
//$('#export').click(function() {
$(".export").on('click', function (event) {
var outputFile = window.prompt("請輸入匯出之檔名") || 'export';
outputFile = outputFile.replace('.csv','') + '.csv'

// CSV
exportTableToCSV.apply(this, [$('#dvData>table'), outputFile]);
});
</script>

2. HTML區塊
<a href='#' class='export'>匯出</a>

<div style="display:none" id="dvData">
  <table>
      <tr><th>標題A</th><th>標題B</th></tr>
      <tr><td>資料A1</td><td>資料B1</td></tr>
      <tr><td>資料A2</td><td>資料B2</td></tr>
  </table>
</div>

沒有留言: