Office JS - Excel,添加数据透视图

问题描述 投票:0回答:2

如何使用 office.js 添加数据透视图?

我可以看到图表的 pivotOptions 属性(https://learn.microsoft.com/en-us/javascript/api/excel/excel.chart?view=excel-js-preview#excel-excel-chart -pivotoptions-member) 但我找不到类似于其他文档页面的数据透视图创建的清晰示例(即 https://learn.microsoft.com/en-us/office/dev/add-ins/excel/excel-add -ins-数据透视表

可能吗?你能告诉我怎么做吗?

excel office-js office-addins excel-web-addins pivot-chart
2个回答
0
投票

尝试一下:

Excel.run(function (context) {
    // Get the active worksheet
    var sheet = context.workbook.worksheets.getActiveWorksheet();
    // Define the data range for the PivotTable
    var dataRange = sheet.getRange("A1:C10");
    // Create a PivotTable based on the data range
    var pivotTable = sheet.pivotTables.add("A15", dataRange, true);
    // Define the data range for the PivotChart
    var chartRange = sheet.getRange("E1:F10");
    // Create a PivotChart based on the PivotTable and data range
    var pivotChart = sheet.charts.add("A30", Excel.ChartType.columnClustered, pivotTable);
    pivotChart.setSourceData(chartRange);
    // Synchronize the changes with the workbook
    return context.sync();
}).catch(function (error) {
    console.log(error);
});

0
投票

我也遇到了同样的问题,静辉的回答不起作用。 有效的是


    const 数据地址 = "C2:D10"; // 你的数据存储在哪里
    const 数据透视表地址 = "A2"; // 您希望在何处创建数据透视表
    const Sheet = context.workbook.worksheets.getActiveWorksheet();

    const 数据透视表 =sheet.pivotTables.add(
        '数据透视表名称',
        数据地址,
        数据透视表地址
    );
    
    // 就我而言,我希望 asset 作为行, amountInMyCurrency 作为数据
    hubTable.rowHierarchies.add(pivotTable.hierarchies.getItem('asset'));
    数据透视表.dataHierarchies.add(
        hubTable.hierarchies.getItem('amountInMyCurrency')
    );
    等待sheet.context.sync();
      
    // 然后我们像任何其他图表一样添加图表,Excel 以某种方式拾取数据透视表,只需添加此数据透视表的任何单元格
    constivotChart=sheet.charts.add(
      Excel.ChartType.columnClustered,
      sheet.getRange(数据透视表地址)
    );
    等待sheet.context.sync();

© www.soinside.com 2019 - 2024. All rights reserved.