Javascript JSON至Excel文件下载 [英] Javascript JSON to Excel file download

查看:138
本文介绍了Javascript JSON至Excel文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Json数据,我需要使用javascript将json数据转换为Excel文件,

I have Json data and i need convert json data to Excel file using javascript,

参考网址: http://jsfiddle.net/hybrid13i/JXrwM/

我正在使用以下代码:

function JSONToTSVConvertor(JSONData, ReportTitle, ShowLabel, myTemplateName){

    //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
    var TSV = '';    
    //Set Report title in first row or line
    //TSV += ReportTitle + '\r\n\n';
    //This condition will generate the Label/Header
    if (ShowLabel) {
        var row = "";
        //This loop will extract the label from 1st index of on array
        for (var index in arrData[0]) {
            //Now convert each value to string and tab-seprated
            row += index + '    ';
        }
        row = row.slice(0, -1);
        //append Label row with line break
        TSV += row + '\r\n';
    }

    //1st loop is to extract each row
    for (var i = 0; i < arrData.length; i++) {
        var row = "";
        //2nd loop will extract each column and convert it in string tab-seprated
        for (var index in arrData[i]) {
            row += '"' + arrData[i][index] + '" ';
        }
        row.slice(0, row.length - 1);
        //add a line break after each row
        TSV += row + '\r\n';
    }

    if (TSV == '') {        
        alert("Invalid data");
        return;
    }   
    var blob = new Blob([TSV], {type: "data:text/tsv;charset=utf-8"});
    //Generate a file name

    var fileName = myTemplateName;
    //this will remove the blank-spaces from the title and replace it with an underscore
    fileName += ReportTitle.replace(/ /g,"_"); 
    saveAs(blob, ""+fileName+".tsv");
}

此示例代码适用于csv和tsv格式.而且我需要Excel格式,我认为没有任何想法请帮助我. 请提供一些示例代码. 谢谢...

this sample code work to csv and tsv format. and i need to Excel format i don't think any idea please help me. pls suggest some example code. Thanks...

推荐答案

CSV是Excel文件本身.但是,在许多语言环境中,上述脚本生成的csv均未正确打开,因此excel将所有内容放入1个单元格中.只需对原始脚本进行一些修改即可:只需将标头替换为"sep =,"即可.

CSV, as said, is excel file itself. But, in many locales, csv generated by the script above is opened incorrectly, where excel puts everything into 1 cell. Small modification of original script helps: just replace header with "sep=,".

var CSV = 'sep=,' + '\r\n\n';

此处具有更改的工作示例: https://jsfiddle.net/1ecj1rtz/.

Working example with change here: https://jsfiddle.net/1ecj1rtz/.

花了一些时间解决这个问题,因此回答旧线程来帮助其他人节省一些时间.

Spent some time figuring this out, and therefore answering old thread to help others save some time.

这篇关于Javascript JSON至Excel文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆