使用javascript创建文件并导出到.dat和.csv

时间:2017-02-18 09:42:36

标签: javascript html data-uri

我想创建并将记录导出到.csv和.dat文件中, 我目前的.csv文件代码是

 window.downloadCSV = function(args) {
    var data, filename, link;

    var csv = convertArrayOfObjectsToCSV({
        data: stockData
    });
    if (csv == null) return;

    filename = args.filename || Xrm.Page.getAttribute("name").getValue() + ".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();
}
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;

    });

    result += "Total";
    result += columnDelimiter;
    result += columnDelimiter;
    result += columnDelimiter;
    result += totalAmount;
    result += columnDelimiter;
    result += totalHash;

    return result;
}

上面的代码在.csv文件中工作,但对于.dat文件,它会生成一个内容为一行文本而不是数据表的文件。

对于.dat文件,我将文件名和csv设置为

filename = args.filename || Xrm.Page.getAttribute("name").getValue() + ".dat";
csv = 'data:text/plain;charset=utf-8,' + csv;

有人可以给我一个建议。

expected result

current result

0 个答案:

没有答案