js导出csv

Use JavaScript to Export Your Dataas CSV

28 MAY 2015 on Javascriptcsvexportdata

101155

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

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

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

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

var stockData = [ 
        {
            Symbol:"AAPL",
            Company: "AppleInc.",
            Price: 132.54
        },
        {
            Symbol:"INTC",
            Company: "IntelCorporation",
            Price: 33.45
        },
        {
            Symbol:"GOOG",
            Company: "GoogleInc",
            Price: 554.52
        },
    ];

Now we need a function that will take any array of objects andcreate 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 tocreate a header row, followed by a newline. Then we loop through each objectand 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 aCSV 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 specialstring that tells the browser that our content is CSV and it needs to bedownloaded:

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 alsoset the download attribute on our link to the filename we want to see for ourdownload stock-data.csv

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

    <ahref='#'
        οnclick='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 browsercalled stock-data.csv and then when you open it, we see the data inthe 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 whatproperties are on your objects. If each object had 100 or 3 properties it wouldwork just as well.

It's also a nifty trick that you can create a download so easilyin the browser. Not all developers know that you can do that. In fact, thatsame 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='#' οnclick='downloadCSV({ filename:"stock-data.csv" });'>Download CSV</a>

<script type="text/javascript"> 
    var stockData = [
        {
            Symbol:"AAPL",
            Company: "AppleInc.",
            Price:"132.54"
        },
        {
            Symbol:"INTC",
            Company: "IntelCorporation",
            Price:"33.45"
        },
        {
            Symbol: "GOOG",
            Company: "GoogleInc",
            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>

 

来自 <http://www.cnblogs.com/oxspirt/p/6589276.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值