好好爱自己!

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 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:

How to Download Data as CSV with JavaScript

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>  
posted @   立志做一个好的程序员  阅读(593)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现

不断学习创作,与自己快乐相处

点击右上角即可分享
微信分享提示