原文: http://halistechnology.com/2015/05/28/use-javascript-to-export-your-data-as-csv/

-----------------------------------------------------

Use JavaScript to Export Your Data as CSV

28 MAY 2015 on Javascriptcsvexportdata

101155

Do you know what annoys me? When I have my data in a web application and I can't get it out. And if you're not giving your users a way to export their data, then they're annoyed too.

Today I'm going to show you how simple it is to provide CSV downloads in your application.

All that's needed is a little Javascript and HTML. You don't need a fancy $2,000 control suite or any server-side code.

First, we need some data. For this example we will turn an array of objects into a CSV download for the user:

var stockData = [
{
Symbol: "AAPL",
Company: "Apple Inc.",
Price: 132.54
},
{
Symbol: "INTC",
Company: "Intel Corporation",
Price: 33.45
},
{
Symbol: "GOOG",
Company: "Google Inc",
Price: 554.52
},
];

Now we need a function that will take any array of objects and create CSV data:

function convertArrayOfObjectsToCSV(args) {
var result, ctr, keys, columnDelimiter, lineDelimiter, data; data = args.data || null;
if (data == null || !data.length) {
return null;
} columnDelimiter = args.columnDelimiter || ',';
lineDelimiter = args.lineDelimiter || '\n'; keys = Object.keys(data[0]); result = '';
result += keys.join(columnDelimiter);
result += lineDelimiter; data.forEach(function(item) {
ctr = 0;
keys.forEach(function(key) {
if (ctr > 0) result += columnDelimiter; result += item[key];
ctr++;
});
result += lineDelimiter;
}); return result;
}

First the function loops through the keys on one of the objects to create a header row, followed by a newline. Then we loop through each object and write out the values of each property.

Here's what you end up with:

Symbol,Company,Price
AAPL,Apple Inc.,132.54
INTC,Intel Corporation,33.45
GOOG,Google Inc,554.52

Now we need a function that will take this data and turn it into a CSV file for download:

function downloadCSV(args) {
var data, filename, link;
var csv = convertArrayOfObjectsToCSV({
data: stockData
});
if (csv == null) return; filename = args.filename || 'export.csv'; if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
data = encodeURI(csv); link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
link.click();
}

This function takes the CSV we created and prepends a special string that tells the browser that our content is CSV and it needs to be downloaded:

data:text/csv;charset=utf-8,

So now we have:

data:text/csv;charset=utf-8,Symbol,Company,Price
AAPL,Apple Inc.,132.54
INTC,Intel Corporation,33.45
GOOG,Google Inc,554.52

We set the href attribute on our link to the above string. We also set the download attribute on our link to the filename we want to see for our download stock-data.csv

Then in our html we have a simple link that we can use to kick off things and test it out:

    <a href='#'
onclick='downloadCSV({ filename: "stock-data.csv" });'
>Download CSV</a>

And when you click this link here's what should happen:

You should get a download in the browser called stock-data.csv and then when you open it, we see the data in the expected table format.

The meat of this example happens in less than 50 lines of code. The code loops through your objects generically, so it doesn't matter what properties are on your objects. If each object had 100 or 3 properties it would work just as well.

It's also a nifty trick that you can create a download so easily in the browser. Not all developers know that you can do that. In fact, that same special string can be modified to allow other types of downloads.

Here's the full example if you want to play with it:

<!doctype html>
<html>
<head></head>
<body> <a href='#' onclick='downloadCSV({ filename: "stock-data.csv" });'>Download CSV</a> <script type="text/javascript">
var stockData = [
{
Symbol: "AAPL",
Company: "Apple Inc.",
Price: "132.54"
},
{
Symbol: "INTC",
Company: "Intel Corporation",
Price: "33.45"
},
{
Symbol: "GOOG",
Company: "Google Inc",
Price: "554.52"
},
]; function convertArrayOfObjectsToCSV(args) {
var result, ctr, keys, columnDelimiter, lineDelimiter, data; data = args.data || null;
if (data == null || !data.length) {
return null;
} columnDelimiter = args.columnDelimiter || ',';
lineDelimiter = args.lineDelimiter || '\n'; keys = Object.keys(data[0]); result = '';
result += keys.join(columnDelimiter);
result += lineDelimiter; data.forEach(function(item) {
ctr = 0;
keys.forEach(function(key) {
if (ctr > 0) result += columnDelimiter; result += item[key];
ctr++;
});
result += lineDelimiter;
}); return result;
} function downloadCSV(args) {
var data, filename, link; var csv = convertArrayOfObjectsToCSV({
data: stockData
});
if (csv == null) return; filename = args.filename || 'export.csv'; if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
data = encodeURI(csv); link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
link.click();
}
</script>
</body>
</html>

Use JavaScript to Export Your Data as CSV的更多相关文章

  1. Use a PowerShell Module to Easily Export Excel Data to CSV

    http://blogs.technet.com/b/heyscriptingguy/archive/2011/07/21/use-a-powershell-module-to-easily-expo ...

  2. HTML save data to CSV or excel

    /********************************************************************************* * HTML save data ...

  3. 利用php CI force_download($filename, $data) 下载.csv 文件解决文件名乱码,文件内容乱码

    利用php CI force_download($filename, $data) 下载.csv 文件解决文件名乱码,文件内容乱码 2014-07-31 12:53 1047人阅读 评论(0) 收藏  ...

  4. [Javascript] Simplify Creating Immutable Data Trees With Immer

    Immer is a tiny library that makes it possible to work with immutable data in JavaScript in a much m ...

  5. [Python] Read and plot data from csv file

    Install: pip install pandas pip install matplotlib # check out the doc from site import pandas as pd ...

  6. asp and javascript: sql server export data to csv and to xls

    <%@LANGUAGE="JAVASCRIPT" CODEPAGE="65001"%> <% //塗聚文 //20131021 functio ...

  7. Export SQLite data to Excel in iOS programmatically(OC)

    //For the app I have that did this, the SQLite data was fairly large. Therefore, I used a background ...

  8. JavaScript 的 export default 命令

    export default 指定模块的默认输出,一个模块只能有一个默认输出. 举个例子. export-default.js export default { name: 'hello', data ...

  9. [WIP]JavaScript import, export

    创建: 2019/06/14 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/import h ...

随机推荐

  1. Windows API函数大全(完整)

    Windows API函数大全,从事软件开发的朋友可以参考下 1. API之网络函数 WNetAddConnection 创建同一个网络资源的永久性连接 WNetAddConnection2 创建同一 ...

  2. 目标检测中bounding box regression

    https://zhuanlan.zhihu.com/p/26938549 RCNN实际包含两个子步骤,一是对上一步的输出向量进行分类(需要根据特征训练分类器):二是通过边界回归(bounding-b ...

  3. Chrome浏览器商店安装的插件保存到本地

    Chrome自67版本开始,不能从第三方下载插件拖动安装,要么就是以前的方法安装修改为zip格式,会有报错(报错如下图),强迫症肯定忍不了报错的:按照网上说法,是第三方插件的压缩算法和Chrome商店 ...

  4. packet capture

    1.下载地址:https://www.coolapk.com/apk/app.greyshirts.sslcapture

  5. mybatis-使用junit测试与main方法测试结果不一致问题

    今天使用ieda写mybatis程序感觉太不友好了,而且也没找到问题所在.问题:写的user.xml中的语句与输出的语句不一样.尝试了各种办法都没有解决. mybatis配置的使用的查询实体.xml ...

  6. 什么是session?

    Session一般译作会话.从不同的层面看待session,它有着类似但不全然相同的含义.比如,在web应用的用户看来,他打开浏览器访问一个电子商务网站,登录.并完成购物直到关闭浏览器,这是一个会话. ...

  7. AT2663 Namori Grundy

    题目描述: luogu 题解: 好多细节,比如说每个点有且仅有一条入边. 所以说这个图一定是一个基环外向树. 考虑只是一个环的情况,我们可以发现,当环长为偶数时我们可以$01$交替染色,但环长为奇数时 ...

  8. 19. REFERENTIAL_CONSTRAINTS

    19. REFERENTIAL_CONSTRAINTS REFERENTIAL_CONSTRAINTS表提供有关外键的信息. REFERENTIAL_CONSTRAINTS有以下列: CONSTRAI ...

  9. 我的Python分析成长之路1

    Python是什么?                                                                                           ...

  10. 一个关于vue+mysql+express的全栈项目(六)------ 聊天模型的设计

    一.数据模型的设计 这里我们先不讨论群聊的模型,指讨论两个人之间的聊天,我们可以把两个人实时聊天抽象为(点对点)的实时通讯,如下图 我们上面的所说的模型其实也就是数据包的模型应该怎么设计,换句话说就是 ...