使用 Excel.js 处理 Excel 文件

javascriptweb developmentfront end technology更新于 2024/8/15 14:24:00

为了使用 Excel.js,您需要先将该包作为依赖项安装在您的项目中。要在您的项目中安装 Excel.js,您需要运行以下命令 -

npm install exceljs

运行上述命令后,Excel.js 将作为依赖项安装在您的项目中。

在本教程中使用的所有示例中,我们将使用"xlsx"文件,这些文件是 Microsoft Excel 中使用的开放 XML 电子表格文件。

处理 ExcelJS 单元格

在下面显示的示例中,我们正在处理 Excel 工作表单元格。要获取特定单元格的引用,我们可以使用 getCell 函数。

请考虑下面显示的代码。

// 读取简单单元格值

const Excel = require('exceljs');
const wb = new Excel.Workbook();
const ws = wb.addWorksheet('My Sheet');

ws.addRows([
   [10, 2, 3, 4, 5],
   [6, 11, 8, 9, 10],
   [10, 11, 12, 14, 15],
   [16, 17, 18, 13, 20]]
);

const valueOne = ws.getCell('B1').value;
console.log(valueOne);

const valueTwo = ws.getCell(1, 1).value;
console.log(valueTwo);

const valueThree = ws.getRow(3).getCell(3).value;
console.log(valueThree);

在这里,我将数据添加到工作表,然后借助 getCell 函数从单元格中读取数据。

关于此示例,有几个要点需要注意,首先是我们正在生成一个使用下面显示的代码片段生成的新工作簿。

const wb = new Excel.Workbook();

现在,我们需要向此 excel 文件添加一个新的工作表,我们使用下面显示的代码片段来完成此操作。

const ws = wb.addWorksheet('My Sheet');

现在,下一步,我们借助 addRows 将数据添加到工作表,然后利用 getCell() 函数提取不同单元格的值。

输出

运行此代码时,它将产生以下输出 −

2
10
12

写入 Excel 文件

在此示例中,我们将数据写入 Excel 文件。请考虑下面显示的代码。

const Excel = require('exceljs');
const fileName = 'myexcel.xlsx';

const wb = new Excel.Workbook();
const ws = wb.addWorksheet('My Sheet');

ws.getCell('A1').value = 'Mukul Latiyan';
ws.getCell('B1').value = 'Software Developer';
ws.getCell('C1').value = new Date().toLocaleString();

const r3 = ws.getRow(3);
r3.values = [1, 2, 3, 4];

wb.xlsx
   .writeFile(fileName)
   .then(() => {
      console.log('file created');
   })
   .catch(err => {
      console.log(err.message);
   });

在本例中,我们使用 excel.js 创建一个名为"myexcel.js"的 Excel 文件。然后我们向该 Excel 文件添加一个名为"My Sheet"的新工作表。最后,我们在"我的工作表"的不同单元格位置插入不同的值。

在第一个示例中,我们一次向一个单元格添加值,然后使用整行添加值,最后插入一个包含不同整数作为值的数组。

在这里,一旦我们将值添加到工作表,下一步就是能够在我们的机器中创建文件,为此我们使用 writeFile() 方法。

运行此代码时,它将创建一个名为"myexcel.xlsx"的 Excel 文件,在该文件中,您将拥有我们插入的所有数据。

从 Excel 文件读取数据

在此示例中,我们将尝试从 excel 文件中读取数据,为此,第一步是使用 readFile() 方法,然后我们需要获取工作表的名称,然后只需使用 getColumn() 方法。当我们能够获得特定方法时,下一步就是简单地迭代该列,我们可以在 eachCell() 方法的帮助下做到这一点。

考虑下面显示的代码。

const Excel = require('exceljs');
const wb = new Excel.Workbook();
const fileName = 'myexcel.xlsx';

wb.xlsx.readFile(fileName).then(() => {

   const ws = wb.getWorksheet('My Sheet');
   c1.eachCell(c => {
      console.log(c.value);
   });

   const c2 = ws.getColumn(2);
   c2.eachCell(c => {
      console.log(c.value);
   });
}).catch(err => {
   console.log(err.message);
});

eachCell() 方法将帮助我们迭代特定列的单元格值,然后我们可以打印每个单元格的值。

在上面的例子中,我们在两列(即"列 1"和"列 2")上使用 eachCell() 函数,然后打印这些列中存在的所有值。

输出

运行此代码时,它将产生以下输出 -

Mukul Latiyan
1
软件开发人员
2

使用列

现在让我们了解一个更复杂的例子,我们将一个 JSON 数据数组添加到列中,然后还将添加多行,然后使用 getColumn() 和 eachCell() 方法获取列中每个单元格的值。

考虑代码如下所示。

const Excel = require('exceljs');

const wb = new Excel.Workbook();
const ws = wb.addWorksheet('My Sheet');

const headers = [{
   header: 'First name',
   key: 'fn',
   width: 15
},
{
   header: 'Last name',
   key: 'ln',
   width: 15
},
{
   header: 'Occupation',
   key: 'occ',
   width: 15
},
{
   header: 'Salary',
   key: 'sl',
   width: 15
},
]

ws.columns = headers;

ws.addRow(['Mukul', 'Latiyan', 'Software Developer', 1230]);
ws.addRow(['Prince', 'Yadav', 'Driver', 980]);
ws.addRow(['Mayank', 'Agarwal', 'Maali', 770]);

ws.getColumn('fn').eachCell((cell, rn) => {
   console.log(cell.value);
});

console.log('--------------');

ws.getColumn('B').eachCell((cell, rn) => {
   console.log(cell.value);
});

console.log('--------------');

ws.getColumn(3).eachCell((cell, rn) => {
   console.log(cell.value);
});

console.log('--------------');
console.log(`There are ${ws.actualColumnCount} columns`);

在此代码中,我们创建了一个名为 headers 的数组,其中有不同的对象,每个对象中都定义了 header、key 和 width,因为这些字段将定义特定单元格的属性,然后我们将此 header 数组分配给列。

之后,我们向这些列添加多行,然后稍后访问每一列,然后使用 eachCell() 方法从特定单元格中获取值。

输出

运行此代码时,它将在终端上产生以下输出 -

First name
Mukul
Prince
Mayank
--------------
Last name
Latiyan
Yadav
Agarwal
--------------
Occupation
Software Developer
Driver
Maali
--------------
There are 4 columns

使用行

现在让我们看看如何在 Excel 上使用特定于行的方法。请考虑下面显示的代码。

const Excel = require('exceljs');

const wb = new Excel.Workbook();
const ws = wb.addWorksheet('My Sheet');

const headers = [{
   header: 'First name',
   key: 'fn',
   width: 15
},
{
   header: 'Last name',
   key: 'ln',
   width: 15
},
{
   header: 'Occupation',
   key: 'occ',
   width: 15
},
{
   header: 'Salary',
   key: 'sl',
   width: 15
},
]

ws.columns = headers;

ws.addRow(['Mukul', 'Latiyan', 'Software Developer', 1230]);
ws.addRow(['Prince', 'Yadav', 'Driver', 980]);
ws.addRow(['Mayank', 'Agarwal', 'Maali', 770]);

console.log(`There are ${ws.actualRowCount} rows`);

let rows = ws.getRows(1, 4).values();

for (let row of rows) {
	row.eachCell((cell, cn) => {
    	console.log(cell.value);
	});
	console.log('--');
}

输出

当您运行此代码时,它将在终端上产生以下输出 -

There are 4 rows
First name
Last name
Occupation
Salary
--
Mukul
Latiyan
Software Developer
1230
--
Prince
Yadav
Driver
980
--
Mayank
Agarwal
Maali
770
--

结论

在本教程中,我们学习了如何借助 Excel.js 处理 Excel 文件以从单元格、行和列中提取值


相关文章