Javascript 在 jQuery 中导出到 csv

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4639372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:23:45  来源:igfitidea点击:

Export to csv in jQuery

javascriptasp.netjquerycsv

提问by Pratik

I am dynamically generating a div which is like :

我正在动态生成一个 div,如下所示:

<div id='PrintDiv'>
        <table id="mainTable">
            <tr>
                <td>
                    Col1
                </td>
                <td>
                    Col2
                </td>
                <td>
                    Col3
                </td>
            </tr>
            <tr>
                <td>
                    Val1
                </td>
                <td>
                    Val2
                </td>
                <td>
                    Val3
                </td>
            </tr>
            <tr>
                <td>
                    Val11
                </td>
                <td>
                    Val22
                </td>
                <td>
                    Val33
                </td>
            </tr>
            <tr>
                <td>
                    Val111
                </td>
                <td>
                    Val222
                </td>
                <td>
                    Val333
                </td>
            </tr>
        </table>
    </div>

And there are lot more elements on the page as well. Now, how can i get a csv file like this :

页面上还有更多元素。现在,我怎样才能得到这样的 csv 文件:

Col1,Col2,Col3
Val1,Val2,Val3
Val11,Val22,Val33
Val111,Val222,Val333

using jQuery ?

使用 jQuery 吗?

need a file save dailog box too,like this :

也需要一个文件保存对话框,像这样:

alt text

替代文字

Thanks.

谢谢。

回答by Italo Borssatto

You can do that in the client side only, in browser that accept Data URIs:

您只能在客户端,在接受数据 URI 的浏览器中执行此操作:

data:application/csv;charset=utf-8,content_encoded_as_url

In your example the Data URI must be:

在您的示例中,数据 URI 必须是:

data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333

You can call this URI by:

您可以通过以下方式调用此 URI:

  • using window.open
  • or setting the window.location
  • or by the href of an anchor
  • by adding the download attribute it will work in chrome, still have to test in IE.
  • 使用 window.open
  • 或设置 window.location
  • 或通过锚点的 href
  • 通过添加下载属性,它可以在 chrome 中工作,仍然需要在 IE 中进行测试。

To test, simply copy the URIs above and paste in your browser address bar. Or test the anchor below in a HTML page:

要进行测试,只需复制上面的 URI 并粘贴到您的浏览器地址栏中。或者在 HTML 页面中测试以下锚点:

<a download="somedata.csv" href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333">Example</a>

To create the content, getting the values from the table, you can use table2CSVand do:

要创建内容,从表中获取值,您可以使用table2CSV并执行以下操作:

var data = $table.table2CSV({delivery:'value'});

$('<a></a>')
    .attr('id','downloadFile')
    .attr('href','data:text/csv;charset=utf8,' + encodeURIComponent(data))
    .attr('download','filename.csv')
    .appendTo('body');

$('#downloadFile').ready(function() {
    $('#downloadFile').get(0).click();
});

Most, if not all, versions of IE don't support navigation to a data link, so a hack must be implemented, often with an iframe. Using an iFramecombined with document.execCommand('SaveAs'..), you can get similar behavior on most currently used versions of IE.

大多数(如果不是全部)版本的 IE 不支持导航到数据链接,因此必须实施 hack,通常使用iframe. 使用一个iFrame联合document.execCommand('SaveAs'..),你可以得到的IE浏览器的大多数目前使用的版本类似的行为。

回答by lepe

This is my implementation (based in: https://gist.github.com/3782074):

这是我的实现(基于:https: //gist.github.com/3782074):

Usage: HTML:

用法:HTML:

<table class="download">...</table>
<a href="" download="name.csv">DOWNLOAD CSV</a>

JS:

JS:

$("a[download]").click(function(){
    $("table.download").toCSV(this);    
});

Code:

代码

jQuery.fn.toCSV = function(link) {
  var $link = $(link);
  var data = $(this).first(); //Only one table
  var csvData = [];
  var tmpArr = [];
  var tmpStr = '';
  data.find("tr").each(function() {
      if($(this).find("th").length) {
          $(this).find("th").each(function() {
            tmpStr = $(this).text().replace(/"/g, '""');
            tmpArr.push('"' + tmpStr + '"');
          });
          csvData.push(tmpArr);
      } else {
          tmpArr = [];
             $(this).find("td").each(function() {
                  if($(this).text().match(/^-{0,1}\d*\.{0,1}\d+$/)) {
                      tmpArr.push(parseFloat($(this).text()));
                  } else {
                      tmpStr = $(this).text().replace(/"/g, '""');
                      tmpArr.push('"' + tmpStr + '"');
                  }
             });
          csvData.push(tmpArr.join(','));
      }
  });
  var output = csvData.join('\n');
  var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(output);
  $link.attr("href", uri);
}

Notes:

注意事项

  • It uses "th" tags for headings. If they are not present, they are not added.
  • This code detects numbers in the format: -####.## (You will need modify the code in order to accept other formats, e.g. using commas).
  • 它使用“th”标签作为标题。如果它们不存在,则不会添加它们。
  • 此代码检测以下格式的数字:-####.##(您需要修改代码以接受其他格式,例如使用逗号)。

UPDATE:

更新

My previous implementation worked fine but it didn't set the csv filename. The code was modified to use a filename but it requires an < a > element. It seems that you can't dynamically generate the < a > element and fire the "click" event (perhaps security reasons?).

我之前的实现工作正常,但没有设置 csv 文件名。代码已修改为使用文件名,但它需要一个 < a > 元素。似乎您无法动态生成 < a > 元素并触发“单击”事件(可能是出于安全原因?)。

DEMO

演示

http://jsfiddle.net/nLj74t0f/

http://jsfiddle.net/nLj74t0f/

(Unfortunately jsfiddle fails to generate the file and instead it throws an error: 'please use POST request', don't let that error stop you from testing this code in your application).

(不幸的是,jsfiddle 无法生成文件,而是抛出错误:“请使用 POST 请求”,不要让该错误阻止您在应用程序中测试此代码)。

回答by Paul

I recently posted a free software library for this: "html5csv.js" -- GitHub

我最近为此发布了一个免费软件库:“html5csv.js”——GitHub

It is intended to help streamline the creation of small simulator apps in Javascript that might need to import or export csv files, manipulate, display, edit the data, perform various mathematical procedures like fitting, etc.

它旨在帮助简化在 Javascript 中创建小型模拟器应用程序的过程,这些应用程序可能需要导入或导出 csv 文件、操作、显示、编辑数据、执行各种数学程序(如拟合等)。

After loading "html5csv.js" the problem of scanning a table and creating a CSV is a one-liner:

加载“html5csv.js”后,扫描表格并创建CSV的问题是单行的:

CSV.begin('#PrintDiv').download('MyData.csv').go();

Here is a JSFiddle demo of your example with this code.

这是带有此代码的示例JSFiddle 演示

Internally, for Firefox/Chrome this is a data URL oriented solution, similar to that proposed by @italo, @lepe, and @adeneo (on another question). For IE

在内部,对于 Firefox/Chrome,这是一个面向数据 URL 的解决方案,类似于@italo、@lepe 和 @adeneo(在另一个问题上)提出的解决方案。IE浏览器

The CSV.begin()call sets up the system to read the data into an internal array. That fetch then occurs. Then the .download()generates a data URL link internally and clicks it with a link-clicker. This pushes a file to the end user.

CSV.begin()调用将系统设置为将数据读入内部数组。然后发生该提取。然后在.download()内部生成一个数据 URL 链接并使用链接点击器点击它。这会将文件推送给最终用户。

According to caniuseIE10 doesn't support <a download=...>. So for IE my library calls navigator.msSaveBlob()internally, as suggested by @Manu Sharma

根据caniuseIE10 不支持<a download=...>. 所以对于 IE,我的库在navigator.msSaveBlob()内部调用,正如@Manu Sharma建议的

回答by mplungjan

Here are two WORKAROUNDSto the problem of triggering downloads from the client only. In later browsers you should look at "blob"

以下是仅从客户端触发下载问题的两种解决方法。在以后的浏览器中,您应该查看“blob”



1. Drag and drop the table

1.拖放表格

Did you know you can simply DRAG your table into excel?

您知道您可以简单地将表格拖入 Excel 吗?

Here is how to select the table to either cut and past or drag

以下是如何选择要剪切和过去或拖动的表格

Select a complete table with Javascript (to be copied to clipboard)

使用 Javascript 选择一个完整的表格(要复制到剪贴板)



2. create a popup page from your div

2. 从你的 div 创建一个弹出页面

Although it will not produce a save dialog, if the resultingpopup is saved with extension .csv, it will be treated correctly by Excel.

虽然它不会产生保存对话框,但如果生成的弹出窗口以扩展名.csv保存,Excel 将对其进行正确处理。

The string could be
w.document.write("row1.1\trow1.2\trow1.3\nrow2.1\trow2.2\trow2.3");
e.g. tab-delimited with a linefeed for the lines.

该字符串可以
w.document.write("row1.1\trow1.2\trow1.3\nrow2.1\trow2.2\trow2.3");
例如用制表符分隔,并带有换行符。

There are plugins that will create the string for you - such as http://plugins.jquery.com/project/table2csv

有插件可以为您创建字符串 - 例如http://plugins.jquery.com/project/table2csv

var w = window.open('','csvWindow'); // popup, may be blocked though
// the following line does not actually do anything interesting with the 
// parameter given in current browsers, but really should have. 
// Maybe in some browser it will. It does not hurt anyway to give the mime type
w.document.open("text/csv");
w.document.write(csvstring); // the csv string from for example a jquery plugin
w.document.close();


DISCLAIMER: These are workarounds, and does not fully answer the question which currently has the answer for most browser: not possible on the client only

免责声明:这些是解决方法,并不能完全回答目前对大多数浏览器都有答案的问题:仅在客户端上不可能

回答by DKSan

By using just jQuery, you cannot avoid a server call.

通过仅使用 jQuery,您无法避免服务器调用。

However, to achieve this result, I'm using Downloadify, which lets me save files without having to make another server call. Doing this reduces server load and makes a good user experience.

但是,为了实现此结果,我使用了Downloadify,它使我无需进行另一个服务器调用即可保存文件。这样做可以减少服务器负载并提供良好的用户体验。

To get a proper CSV you just have to take out all the unnecessary tags and put a ',' between the data.

要获得正确的 CSV,您只需去掉所有不必要的标签并在数据之间放置一个“,”。

回答by Nick Craver

You can't avoid a server call here, JavaScript simply cannot (for security reasons) save a file to the user's file system. You'll have to submit your data to the server and have itsend the .csvas a link or an attachment directly.

您无法避免此处的服务器调用,JavaScript 根本无法(出于安全原因)将文件保存到用户的文件系统。您必须将数据提交到服务器,并让它.csv直接作为链接或附件发送。

HTML5 has someability to do this(though saving really isn't specified - just a use case, you can readthe file if you want), but there's no cross-browser solution in place now.

HTML5 有一些能力来做到这一点(尽管确实没有指定保存 - 只是一个用例,如果需要,您可以读取文件),但是现在没有跨浏览器的解决方案。

回答by ManiMaran A

Just try the following coding...very simple to generate CSV with the values of HTML Tables. No browser issues will come

只需尝试以下编码...使用 HTML 表的值生成 CSV 非常简单。不会出现浏览器问题

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>        
        <script src="http://www.csvscript.com/dev/html5csv.js"></script>
<script>
$(document).ready(function() {

 $('table').each(function() {
    var $table = $(this);

    var $button = $("<button type='button'>");
    $button.text("Export to CSV");
    $button.insertAfter($table);

    $button.click(function() {     
         CSV.begin('table').download('Export.csv').go();
    });
  });  
})

</script>
    </head>
<body>
<div id='PrintDiv'>
<table style="width:100%">
  <tr>
    <td>Jill</td>
    <td>Smith</td>      
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Hymanson</td>        
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>        
    <td>80</td>
  </tr>
</table>
</div>
</body>
</html>

回答by dabeng

Hope the following demo can help you out.

希望下面的演示可以帮到你。

$(function() {
  $("button").on('click', function() {
    var data = "";
    var tableData = [];
    var rows = $("table tr");
    rows.each(function(index, row) {
      var rowData = [];
      $(row).find("th, td").each(function(index, column) {
        rowData.push(column.innerText);
      });
      tableData.push(rowData.join(","));
    });
    data += tableData.join("\n");
    $(document.body).append('<a id="download-link" download="data.csv" href=' + URL.createObjectURL(new Blob([data], {
      type: "text/csv"
    })) + '/>');


    $('#download-link')[0].click();
    $('#download-link').remove();
  });
});
table {
  border-collapse: collapse;
}

td,
th {
  border: 1px solid #aaa;
  padding: 0.5rem;
  text-align: left;
}

td {
  font-size: 0.875rem;
}

.btn-group {
  padding: 1rem 0;
}

button {
  background-color: #fff;
  border: 1px solid #000;
  margin-top: 0.5rem;
  border-radius: 3px;
  padding: 0.5rem 1rem;
  font-size: 1rem;
}

button:hover {
  cursor: pointer;
  background-color: #000;
  color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id='PrintDiv'>
  <table id="mainTable">
    <tr>
      <td>Col1</td>
      <td>Col2</td>
      <td>Col3</td>
    </tr>
    <tr>
      <td>Val1</td>
      <td>Val2</td>
      <td>Val3</td>
    </tr>
    <tr>
      <td>Val11</td>
      <td>Val22</td>
      <td>Val33</td>
    </tr>
    <tr>
      <td>Val111</td>
      <td>Val222</td>
      <td>Val333</td>
    </tr>
  </table>
</div>

<div class="btn-group">
  <button>csv</button>
</div>