2015-04-14 156 views
1

我正在開發一個asp.net mvc5 web應用程序。我需要實現將Html表導出爲.csv文件的功能。所以我說下面的鏈接: -將html表導出爲CSV文件,總是返回空文件

<a href="#" class="export">Export Table data into Excel</a>

,我有以下腳本: -

$(document).ready(function() { 

    function exportTableToCSV($table, filename) { 

     var $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 
      csv = '"' + $rows.map(function (i, row) { 
       var $row = $(row), 
        $cols = $row.find('td'); 

       return $cols.map(function (j, col) { 
        var $col = $(col), 
         text = $col.text(); 

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

       }).get().join(tmpColDelim); 

      }).get().join(tmpRowDelim) 
       .split(tmpRowDelim).join(rowDelim) 
       .split(tmpColDelim).join(colDelim) + '"', 

      // Data URI 
      csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv); 

     $(this) 
      .attr({ 
       'download': filename, 
       'href': csvData, 
       'target': '_blank' 
      }); 
    } 

    // This must be a hyperlink 
    $(".export").on('click', function (event) { 
     // CSV 
     exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']); 

     // IF CSV, don't do event.preventDefault() or return false 
     // We actually need this to be a typical hyperlink 
    }); 
}); 

,我使用的tabletoCSV插件在這個link,如下: -

jQuery.fn.table2CSV = function (options) { 
    var options = jQuery.extend({ 
     separator: ',', 
     header: [], 
     delivery: 'popup' // popup, value 
    }, 
    options); 

    var csvData = []; 
    var headerArr = []; 
    var el = this; 

    //header 
    var numCols = options.header.length; 
    var tmpRow = []; // construct header avalible array 

    if (numCols > 0) { 
     for (var i = 0; i < numCols; i++) { 
      tmpRow[tmpRow.length] = formatData(options.header[i]); 
     } 
    } else { 
     $(el).filter(':visible').find('th').each(function() { 
      if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html()); 
     }); 
    } 

    row2CSV(tmpRow); 

    // actual data 
    $(el).find('tr').each(function() { 
     var tmpRow = []; 
     $(this).filter(':visible').find('td').each(function() { 
      if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html()); 
     }); 
     row2CSV(tmpRow); 
    }); 
    if (options.delivery == 'popup') { 
     var mydata = csvData.join('\n'); 
     return popup(mydata); 
    } else { 
     var mydata = csvData.join('\n'); 
     return mydata; 
    } 

    function row2CSV(tmpRow) { 
     var tmp = tmpRow.join('') // to remove any blank rows 
     // alert(tmp); 
     if (tmpRow.length > 0 && tmp != '') { 
      var mystr = tmpRow.join(options.separator); 
      csvData[csvData.length] = mystr; 
     } 
    } 
    function formatData(input) { 
     // replace " with “ 
     var regexp = new RegExp(/["]/g); 
     var output = input.replace(regexp, "“"); 
     //HTML 
     var regexp = new RegExp(/\<[^\<]+\>/g); 
     var output = output.replace(regexp, ""); 
     if (output == "") return ''; 
     return '"' + output + '"'; 
    } 
    function popup(data) { 
     var generator = window.open('', 'csv', 'height=400,width=600'); 
     generator.document.write('<html><head><title>CSV</title>'); 
     generator.document.write('</head><body >'); 
     generator.document.write('<textArea cols=70 rows=15 wrap="off" >'); 
     generator.document.write(data); 
     generator.document.write('</textArea>'); 
     generator.document.write('</body></html>'); 
     generator.document.close(); 
     return true; 
    } 
}; 

當前我得到以下標記,其中顯示了一個表和導出超鏈接: -

<table id="dvData" class= "table table-striped table-bordered bootstrap-datatable datatable"> 
    <tr> 
     <th></th> 
     <th> 
      Name 
     </th> 
     <th class="hidden-phone hidden-tablet"> 
      Description 
     </th> 
     <th> 
      User Groups 
     </th> 
     <th> 
      Security Roles 
     </th> 
     <th class="hidden-phone hidden-tablet"> 

     </th> 
    </tr> 

    <tr id = "234"> 
     <td> 
      <a href="/SecurityGroup/Edit/234">Edit</a> 
| 
<a data-ajax="true" data-ajax-confirm="Are You sure You want to delete (de)" data-ajax-failure="deletionerror" data-ajax-method="Post" data-ajax-success="deletionconfirmation" href="/SecurityGroup/Delete/234">Delete</a> </td> 
     <td> 
      <a href="/SecurityGroup/Details/234">de</a> 
     </td> 
     <td class="hidden-phone hidden-tablet"> 
      d 
     </td> 
     <td> 
      The are <a href="/SecurityGroup/Details/234">0</a> Users. 

     </td> 
     <td> 

     </td> 
     <td class="center hidden-phone hidden-tablet"> 



      <a class="btn btn-success" href="/SecurityGroup/Details/234"> 
    <i class="icon-zoom-in icon-white"></i> 
    Details 
    </a> 

     </td> 
    </tr> 
    <tr id = "233"> 
     <td> 
      <a href="/SecurityGroup/Edit/233">Edit</a> 
    </td> 
     <td> 
      <a href="/SecurityGroup/Details/233">only me</a> 
     </td> 
     <td class="hidden-phone hidden-tablet"> 

     </td> 
     <td> 
      The are <a href="/SecurityGroup/Details/233">10</a> Users. 

     </td> 
     <td> 

     </td> 
     <td class="center hidden-phone hidden-tablet"> 



      <a class="btn btn-success" href="/SecurityGroup/Details/233"> 
    <i class="icon-zoom-in icon-white"></i> 
    Details 
    </a> 

     </td> 
    </tr> 
    <tr id = "230"> 
     <td> 
      <a href="/SecurityGroup/Edit/230">Edit</a> 
| 
<a data-ajax="true" data-ajax-confirm="Are You sure You want to delete (rwerwe)" data-ajax-failure="deletionerror" data-ajax-method="Post" data-ajax-success="deletionconfirmation" href="/SecurityGroup/Delete/230">Delete</a> </td> 
     <td> 
      <a href="/SecurityGroup/Details/230">rwerwe</a> 
     </td> 
     <td class="hidden-phone hidden-tablet"> 

     </td> 
     <td> 
      The are <a href="/SecurityGroup/Details/230">0</a> Users. 

     </td> 
     <td> 

     </td> 
     <td class="center hidden-phone hidden-tablet"> 



      <a class="btn btn-success" href="/SecurityGroup/Details/230"> 
    <i class="icon-zoom-in icon-white"></i> 
    Details 
    </a> 

     </td> 
    </tr> 
    <tr id = "231"> 
     <td> 
      <a href="/SecurityGroup/Edit/231">Edit</a> 
    </td> 
     <td> 
      <a href="/SecurityGroup/Details/231">users</a> 
     </td> 
     <td class="hidden-phone hidden-tablet"> 

     </td> 
     <td> 
      The are <a href="/SecurityGroup/Details/231">1</a> Users. 

     </td> 
     <td> 

     </td> 
     <td class="center hidden-phone hidden-tablet"> 



      <a class="btn btn-success" href="/SecurityGroup/Details/231"> 
    <i class="icon-zoom-in icon-white"></i> 
    Details 
    </a> 

     </td> 
    </tr> 
    <tr id = "232"> 
     <td> 
      <a href="/SecurityGroup/Edit/232">Edit</a> 
    </td> 
     <td> 
      <a href="/SecurityGroup/Details/232">w</a> 
     </td> 
     <td class="hidden-phone hidden-tablet"> 
      w 
     </td> 
     <td> 
      The are <a href="/SecurityGroup/Details/232">5</a> Users. 

     </td> 
     <td> 

     </td> 
     <td class="center hidden-phone hidden-tablet"> 



      <a class="btn btn-success" href="/SecurityGroup/Details/232"> 
    <i class="icon-zoom-in icon-white"></i> 
    Details 
    </a> 

     </td> 
    </tr> 

</table></div></div></div> 


<a href="#" class="export">Export Table data into Excel</a> </section> 

但當我點擊導出超鏈接,我保存文檔;文檔大小將只有1 kb,當我用excel打開它時顯示空白表格,如果我用記事本打開它,它會顯示"" 所以任何人都可以使用?

+0

將來請使用[tag:asp.net-mvc-5]標籤; mvc5是一個空標記,應該儘快刪除。 –

回答

2

我會在底部留下一個工作小提琴示例。

是需要一些工作,主要的部分:

exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']); 

要:

exportTableToCSV.apply(this, [$('#dvData'), 'export.csv']); 

然後,它是將結果格式化的問題:

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

// Grab text from table into CSV formatted string 
csv = $rows.map(function (i, row) { 
      var $row = $(row), 
       $cols = $row.find('td'); 
      return $cols.map(function (j, col) { 
       var $col = $(col), 
        text = '"' + $col.text().replace(/(\r\n|\n|\r)/gm,"").trim() + '"'; 
       return text //.replace('"', '""'); // escape double quotes 
      }).get().join(tmpColDelim); 
     }).get().join(tmpRowDelim) 
      .split(tmpRowDelim).join(rowDelim) 
      .split(tmpColDelim).join(colDelim), 

現在返回逗號分隔的列表,其中每列用引號括起來。在jsFiddle

示例,我將離開微調給你。

+0

感謝您的回覆,我會嘗試您的代碼在我的應用程序內,但首先我嘗試了IE上的jsFiddle示例,當我點擊導出鏈接時,它沒有顯示打開的對話框,而是我被重定向到URL = data:application/csv; charset = utf-8,%22Edit%20%7CDelete%22%2C%22de%22%2C%22d%22%2C%22The%20are%200%20Users。%22%2C% 22%22%2C%22Details%22%0D%0A%22Edit%22%2C%22only%20me%22%2C%22%22%2C%二條%20頃%2010%20Users。%22%2C%22%22 %2C%22Details%22%0D%0A%22Edit%20%7CDetete%22%2C%22werwe%22%2C%22%22%2C%22 .. –

+0

這就是奇怪的@johnG,但必須(可能)是一個bug在插件內。你看到的網址實際上並不奇怪,它是''href':csvData'的內容,並且在Chrome中也是如此。在某種意義上,這種方式會以成功的方式發送到Chrome,而IE只會獲取網址。我不能說爲什麼,但插件看起來很舊(在一個例子中引用jQuery 1.3.1) – Mackan