【问题标题】:save a transpose JSON to excel sheet将转置 JSON 保存到 Excel 工作表
【发布时间】:2020-08-03 22:59:12
【问题描述】:

我正在尝试对 JSON 进行转置并将其保存到 excel 表中:

function transpose(a) {
    return Object.keys(a[0]).map(function(c) {
        return a.map(function(r) { return r[c]; });
    });
}

//example for JSON (in the program I get a long JSON in this shape)
const sheet_arr = [{'param1': 1, 'param2': 2},{'param1': 3, 'param2': 4},{'param1': 5, 'param2': 6}] 
 
var temp_ws = xls.utils.json_to_sheet(transpose(sheet_arr));
wb.Sheets['test'] = temp_ws;

在我得到的 excel 表中:

 __________________
|  0  |  1  |  2  |
-------------------
|  1  |  3  |  5  | 
|  2  |  4  |  6  | 
-------------------

我想要这个:

 _____________________________
|  param1  |  1  |  3  |  5  |
|  param2  |  2  |  4  |  6  |
------------------------------

如何轻松获得?

【问题讨论】:

    标签: javascript json excel xlsx


    【解决方案1】:

    这应该可以得到你想要的内容:

    function transpose(a) {
        return Object.keys(a[0]).map(function(c) {
          let ret=a.map(function(r) { return r[c]; });
          ret.unshift(c); return ret;
        });
    };
    
    // or in ES6 notation:
    const transp = a => Object.keys(a[0]).map(c=>{
      let ret=a.map(r=>r[c]); ret.unshift(c); 
      return ret; });
    
    //example for JSON (in the program I get a long JSON in this shape)
    const sheet_arr = [{'param1': 1, 'param2': 2},{'param1': 3, 'param2': 4},{'param1': 5, 'param2': 6}] ;
    
    console.log(transpose(sheet_arr));
    console.log(transp(sheet_arr));
    .as-console-wrapper {max-height:100% !important}

    我只是将键添加为每行中的第一个元素,使用 Array.unshift()

    【讨论】:

    • 谢谢!它仍然显示第一行索引(0 1 2 3),我怎样才能将它从 JSON/Ecxel 中删除,使其完全符合要求?
    • 这一定发生在xls.utils.json_to_sheet() 电话中。我还没有对xls.utils 做过任何事情,但也许以下内容会对您有所帮助? stackoverflow.com/questions/47424755/…
    • 谢谢,正确的方法是var temp_ws = xls.utils.json_to_sheet(transpose(sheet_arr), {skipHeader: 1});
    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 2020-02-20
    • 2020-12-13
    相关资源
    最近更新 更多