Use JavaScript to Export Your Data as CSV
原文: 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 Javascript, csv, export, data
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的更多相关文章
- 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 ...
- HTML save data to CSV or excel
/********************************************************************************* * HTML save data ...
- 利用php CI force_download($filename, $data) 下载.csv 文件解决文件名乱码,文件内容乱码
利用php CI force_download($filename, $data) 下载.csv 文件解决文件名乱码,文件内容乱码 2014-07-31 12:53 1047人阅读 评论(0) 收藏 ...
- [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 ...
- [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 ...
- asp and javascript: sql server export data to csv and to xls
<%@LANGUAGE="JAVASCRIPT" CODEPAGE="65001"%> <% //塗聚文 //20131021 functio ...
- 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 ...
- JavaScript 的 export default 命令
export default 指定模块的默认输出,一个模块只能有一个默认输出. 举个例子. export-default.js export default { name: 'hello', data ...
- [WIP]JavaScript import, export
创建: 2019/06/14 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/import h ...
随机推荐
- 联玛客(W 笔试)
纸质算法题 1. 输入数据:1.3.2.4.8... 输出数据:3.1.4.2.8... 找出规律,写出一个程序求解,并附上时间复杂度和空间复杂度 我的答案: 规律一:奇偶位互换 假设输入数据长度为5 ...
- 初识WEBGL
WEBGL (全写Web Graphics Library)是一种3D绘图协议,这种绘图技术标准允许把JavaScript和OpenGL ES 2.0结合在一起,通过增加OpenGL ES 2.0的一 ...
- Python基础2 列表 元祖 字符串 字典 集合 文件操作 -DAY2
本节内容 列表.元组操作 字符串操作 字典操作 集合操作 文件操作 字符编码与转码 1. 列表.元组操作 列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储.修改等操作 定义列表 ...
- flask学习规划
实现基本登录注册: 留言板功能: 并且部署到服务器: 预计完成时间6.16:. 后续页面美化: 各种其他功能的探索一个月时间: 并行地学习python,java,css,html,js,sql 暑假预 ...
- 【转】Delphi 文件读写
procedure TForm1.Button1Click(Sender: TObject); variFileHandle: Integer;iFileLength: Integer;iBytesR ...
- Liskon替换原则
肯定有不少人跟我刚看到这项原则的时候一样,对这个原则的名字充满疑惑.其实原因就是这项原则最早是在1988年,由麻省理工学院的一位姓里的女士(Barbara Liskov)提出来的. 定义1:如果对每一 ...
- 单点登录-CAS
使用插件 phpCAS ,插件链接:https://github.com/apereo/phpCAS 1. CAS 单点登录流程及插件的API的简介 图片链接来源于wiki:https://wiki. ...
- Django框架基础知识09-请求与响应
视图函数接受到的request到底是个什么对象呢? HttpRequest对象: 服务器接收到http协议的请求后,会根据报文创建HttpRequest对象视图函数的第一个参数是HttpRequest ...
- Python-接口自动化(十一)
配置文件的作用(十一) (十二)配置文件 1.python当中有一个模块可以读取配置文件里面的信息:configparser,对这个模块进行导入之后就可以使用了,import configparser ...
- Oracle开启和关闭的四种模式
>1 启动数据库 在cmd命令窗口,直接输入"sqlplus",直接进入oracle管理界面,输入用户名和密码后,开始启动数据库,启动数据库三个步骤:启动实例.加载数据库.打 ...