本指南介绍如何在 Node.js 中创建 Excel 表。它包含使用给定资源设置开发环境的详细信息、实现该功能的步骤列表以及在 Node.js 中生成 Excel 表的示例代码。您将通过设置不同的参数来了解各种细节以自定义表。
在 Node.js 中将表添加到 Excel 的步骤
- 设置 IDE 以使用 Aspose.Cells for Node.js 通过 Java 创建表
- 使用 Workbook 类创建或加载 Excel 文件以添加表
- 访问工作簿中的工作表并为表添加列表对象
- 使用 TableStyleType 枚举器设置所需的表格样式
- 设置标志以显示所有数字列的总计
- 设置标志以显示特定列的行数
- 保存生成的 Excel 文件
上述步骤定义了如何在 Node.js 中制作 Excel 表格。通过初始化或加载 Excel 文件、访问工作表以及为一系列数据和数据标题信息创建列表对象来启动该过程。添加表格后,设置表格样式和标志以显示特定列的总计和计算类型。
在 Node.js 中创建 Excel 表的代码
const asposecells = require('aspose.cells'); | |
const workbook = new asposecells.Workbook(); | |
// Function to create sample data | |
function createSampleData(sheet) { | |
const titles = ["Employee", "Quarter", "Product", "Country", "Sale"]; | |
const employees = ["David", "James", "Miya"]; | |
const products = ["Chai", "Chang", "Geitost", "Maxilaku"]; | |
const countries = ["USA", "China", "Turkiye", "Germany", "India", "Italy"]; | |
titles.forEach((title, idx) => { | |
sheet.getCells().get(0, idx).setValue(title); | |
}); | |
for (let i = 1; i < 20; i++) { | |
sheet.getCells().get(i, 0).setValue(employees[Math.floor(Math.random() * employees.length)]); | |
sheet.getCells().get(i, 1).setValue(Math.floor(Math.random() * 4) + 1); | |
sheet.getCells().get(i, 2).setValue(products[Math.floor(Math.random() * products.length)]); | |
sheet.getCells().get(i, 3).setValue(countries[Math.floor(Math.random() * countries.length)]); | |
sheet.getCells().get(i, 4).setValue(Math.floor(Math.random() * 2001)); | |
} | |
} | |
// Create sample data if workbook has no data | |
createSampleData(workbook.getWorksheets().get(0)); | |
const sheet = workbook.getWorksheets().get(0); | |
// Add a new list object with 20 rows and 5 columns | |
const listObject = sheet.getListObjects().get(sheet.getListObjects().add("A1", "E20", true)); | |
// Set table style | |
listObject.setTableStyleType(asposecells.TableStyleType.TABLE_STYLE_MEDIUM_10); | |
// Show totals | |
listObject.setShowTotals(true); | |
// Set the second column calculation type | |
listObject.getListColumns().get(1).setTotalsCalculation(asposecells.TotalsCalculation.COUNT); | |
// Save the Excel file | |
workbook.save("output.xlsx"); | |
console.log("Table created successfully!!!"); |
此代码显示如何在 Node.js 中的 Excel 中创建表格。 createSampleData() 是一个可选函数,仅在表没有可用数据时使用。使用 TableStyleType 枚举器设置表格样式,并使用 TotalsCalculation 枚举器设置 TotalsCalculation 类型。
本主题解释了在 Node.js* 中使用 *MS Excel 表。要将各种颜色主题应用于一系列单元格,请参阅有关 使用 Node.js 应用 Excel 主题 的文章。