如何使用 Node.js 在 Excel 中创建图表

本简短教程将指导 如何使用 Node.js 在 Excel 中创建图表。它包含有关 IDE 设置的详细信息、编程任务列表以及用于使用 Node.js 在 Excel 中创建图形的可运行示例代码。您将学习自定义输出图表的不同属性以及生成其他类型图表的选项。

使用 Node.js 创建 Excel 图表的步骤

  1. 将环境设置为 通过 Java 将 Aspose.Cells 用于 Node.js 以创建图表
  2. 创建一个 workbook 并使用 Cells 集合将示例数据填充到选定的工作表中
  3. 在所选工作表中创建一个栏 chart
  4. 设置数据系列和类别
  5. 设置图表标题和标志以显示数据标签
  6. 保存其中包含条形图的工作簿

这些步骤解释了使用 Node.js 创建*Excel 图表和图形的过程。该过程首先创建一个工作簿,在其中添加示例数据,然后创建一个图表,然后设置图表的数据系列和类别。在保存生成的 Excel 文件之前,还会设置图表标题和显示数据标签的标志。

使用 Node.js 创建 Excel 图表的代码

var aspose = aspose || {};
aspose.cells = require("aspose.cells");
//Set the license
new aspose.cells.License().setLicense("License.lic");
// Create a workbook
var wb = new aspose.cells.Workbook();
// Access the first sheet
var sheet = wb.getWorksheets().get(0);
// Get the worksheet cells
var cells = sheet.getCells();
// Fill some sample data
cells.get("B1").putValue("Mountains");
cells.get("B2").putValue("Mount Everest");
cells.get("B3").putValue("K2");
cells.get("B4").putValue("Kangchenjunga");
cells.get("B5").putValue("Lhotse");
cells.get("C1").putValue("Height(m)");
cells.get("C2").putValue(8848);
cells.get("C3").putValue(8611);
cells.get("C4").putValue(8586);
cells.get("C5").putValue(8516);
// Create a Bar chart
var chart_Index = 0;
chart_Index = sheet.getCharts().add(aspose.cells.ChartType.BAR, 7, 1, 34, 13);
var chart = sheet.getCharts().get(chart_Index);
// Set the data series and category
chart.getNSeries().add("C2:C5", true);
chart.getNSeries().setCategoryData("B2:B5");
// Set chart title
chart.getTitle().setText("Mountains By Height");
// Show data labels
let dataLabels;
for (let i = 0; i < chart.getNSeries().getCount(); i++)
{
dataLabels = chart.getNSeries().get(i).getDataLabels();
dataLabels.setShowValue(true);
}
// Save the workbook
wb.save("bar_chart.xlsx");
console.log("Chart generated successfully");

上面的代码演示了使用 Node.js 在 Excel 中创建条形图。您可以使用支持 AREA、BUBBLE、COLUMN、CONE、CYLINDER、FUNNEL 和 PIE 的 ChartType 枚举器创建其他类型的图表。如果要将图表另存为 PDF 或图像,请分别使用图表类中的 toPdf() 和 toImage() 方法。

本文教我们使用 Node.js 在 Excel 中创建条形图。如果您想了解将 Excel 文件转换为 XPS 文件的过程,请参阅 如何使用 Node.js 将 Excel 转换为 XPS 上的文章。

 简体中文