JSON 到 javascript 中的 excel 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27099325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:56:20  来源:igfitidea点击:

JSON to excel file in javascript

javascript

提问by Renuka Thakur

I am using the following code to create excel file data from JSON object and then download it on the click of a button.

我使用以下代码从 JSON 对象创建 excel 文件数据,然后单击按钮下载它。

getExcelFile: function() {
            testJson = validation_data;
            testTypes = {
                "name": "String",
                "city": "String",
                "country": "String",
                "birthdate": "String",
                "amount": "Number"
            };

            emitXmlHeader = function() {
                return '<?xml version="1.0"?>\n' +
                        '<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">\n' +
                        '<ss:Worksheet ss:Name="Sheet1">\n' +
                        '<ss:Table>\n\n';
            };

            emitXmlFooter = function() {
                return '\n</ss:Table>\n' +
                        '</ss:Worksheet>\n' +
                        '</ss:Workbook>\n';
            };

            jsonToSsXml = function(jsonObject) {
                var row;
                var col;
                var xml;
                var data = typeof jsonObject != "object"
                        ? JSON.parse(jsonObject)
                        : jsonObject;

                xml = emitXmlHeader();

                for (row = 0; row < data.length; row++) {
                    xml += '<ss:Row>\n';

                    for (col in data[row]) {
                        xml += '  <ss:Cell>\n';
                        xml += '    <ss:Data ss:Type="' + testTypes[col] + '">';
                        xml += data[row][col] + '</ss:Data>\n';
                        xml += '  </ss:Cell>\n';
                    }

                    xml += '</ss:Row>\n';
                }

                xml += emitXmlFooter();
                return xml;
            };
            download = function(content, filename, contentType) {
                if (!contentType)
                    contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                var a = document.getElementById('test');
                var blob = new Blob([content], {
                    'type': contentType
                });
                a.href = window.URL.createObjectURL(blob);
                a.download = filename;
            };

            download(jsonToSsXml(testJson), 'validation_data.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        }

But the file created doesn't open in Microsoft Office 2007 and gives the error 'File may be corrupt'. Please help.

但创建的文件无法在 Microsoft Office 2007 中打开并给出错误“文件可能已损坏”。请帮忙。

回答by Sujit Kumar Singh

I recently got a solution for this question using AlaSQL.

我最近使用AlaSQL得到了这个问题的解决方案。

Their working example.

他们的工作示例

var sheet_1_data = [{Col_One:1, Col_Two:11}, {Col_One:2, Col_Two:22}];
var sheet_2_data = [{Col_One:10, Col_Two:110}, {Col_One:20, Col_Two:220}];
var opts = [{sheetid:'Sheet One',header:true},{sheetid:'Sheet Two',header:false}];
var res = alasql('SELECT * INTO XLSX("sample_file.xlsx",?) FROM ?', [opts,[sheet_1_data ,sheet_2_data]]);

Libraries required:

需要的库:

<script src="http://alasql.org/console/alasql.min.js"></script> 
<script src="http://alasql.org/console/xlsx.core.min.js"></script> 

NOTE: Don't pass undefined values to the function. Generated file will produce warning messages if you try to open them in this case.

注意:不要将未定义的值传递给函数。如果您在这种情况下尝试打开生成的文件,则会生成警告消息。

Other options were able to convert JSON to CSV (not XLSX).

其他选项能够将 JSON 转换为 CSV(不是 XLSX)。