原文: 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. iview table的render()函数基本的用法

    render:(h,params) => { return h(" 定义的元素 ",{ 元素的性质 }," 元素的内容"/[元素的内容]) }

  2. NetBeans 默认编码修改方法

    如果要NetBeans用UTF-8对文件进行解码,需要修改配置文件,具体方法如下: 1. 找到你的Netbeans安装目录下的etc文件夹,如D:\Program Files\NetBeans 8.2 ...

  3. Linux-02 Linux常用命令

    学习要点 用户切换 网络设置 目录操作 挂载 文件操作 用户切换 登陆时候选择其他用户为root则默认密码和系统默认用户一致 例如设置用户为centos1,密码为centos1,则root用户的密码同 ...

  4. 16.04 下修改 ssh 默认端口

    打开/etc/ssh/ssh_config,在Port指令下追加新的端口设置: Port 8888 即允许通过端口 8888 进行 ssh 访问. 打开/etc/ssh/sshd_config,进行同 ...

  5. Git Bash 常用指令

    1. 关于git bash常用指令 推荐博客: 史上最简单的 GitHub 教程  猴子都能懂的GIT入门 Learn Version Control with Git for Free Git Do ...

  6. linux批量检测服务器能否ping通和硬盘容量状态并抛出报警的一个脚本-附详细解释

    有一些linux基础,最近刚开始学shell,参考了阿良老师的一个监测服务器硬盘状态的脚本,自己进行了一些扩展,今天比较晚了,后边会把注释放上来,感觉脚本还很不完善,希望大家一起探讨一下,共同学习 2 ...

  7. WCF未找到终结点

    配置都配了,仍然找不到,config文件没有重新加载,原因不详,只能重新编译一下,就好了....后续找找原因看看

  8. 剑指Offer(书):旋转数组的最小数字

    题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转. 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素. 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转, ...

  9. 3D地形中的道路模拟

    笔者注: 这篇文章是我本人在2009年发表在cppblog的一篇技术文章,由于我的技术博客迁移至博客园,所以转载到了此,非盗文. 以下是正文: 前段时间被项目组长委派实现基于3D地形的道路系统.实现的 ...

  10. 七、整合SQL基础和PL-SQL基础

    --Oracle数据库重要知识点整理 2017-01-24 soulsjie 目录 --一.创建及维护表... 2 --1.1 创建... 2 --1.2 维护表... 2 --二.临时表的分类.创建 ...