在 TypeScript 中操作 Excel:库概览与实践示例
TypeScript 是 JavaScript 的强类型扩展,广泛应用于 Web 开发,尤其是在构建复杂的企业级应用时。常见的任务之一就是操作 Excel 表格:读取数据、生成报告、导出和导入。在本文中,我们将介绍在 TypeScript 中操作 Excel 的主要库,并提供实用的代码示例。
在 TypeScript 中操作 Excel 的流行库
目前,有几种稳定的解决方案。我们来看三个最受欢迎的:
- ExcelJS — 用于读取、创建和编辑 XLSX 文件的强大库。支持样式、公式、图表、工作表保护等众多功能。可在浏览器和 Node.js 中运行。
- xlsx (SheetJS) — 用于解析和生成表格的轻量级库。非常适合无需复杂格式的快速数据处理。
- node-xlsx — 一个简单的 xlsx 封装,专注于 Node.js。便于快速导出数据数组。
在本指南中,我们将重点介绍 ExcelJS,因为它提供了对文档结构和样式的最大控制。
安装与配置
首先,通过 npm 安装该库:
npm install exceljsnpm install @types/node --save-dev // 用于 Node.js 类型同时,请确保您的项目中已配置好 TypeScript(tsconfig.json 文件)。
创建一个简单的 Excel 文件
创建包含标题和数据的文件示例:
import * as ExcelJS from 'exceljs';
async function createWorkbook() { const workbook = new ExcelJS.Workbook(); const sheet = workbook.addWorksheet('员工');
// 标题 sheet.columns = [ { header: 'ID', key: 'id', width: 10 }, { header: '姓名', key: 'name', width: 25 }, { header: '职位', key: 'position', width: 20 }, { header: '薪资', key: 'salary', width: 15 }, ];
// 数据 const employees = [ { id: 1, name: '伊万·彼得罗夫', position: '开发人员', salary: 150000 }, { id: 2, name: '玛丽亚·斯米尔诺娃', position: '设计师', salary: 120000 }, { id: 3, name: '阿列克谢·库兹涅佐夫', position: '经理', salary: 130000 }, ];
employees.forEach(emp => sheet.addRow(emp));
// 保存 await workbook.xlsx.writeFile('employees.xlsx'); console.log('文件已创建!');}
createWorkbook();从 Excel 读取数据
读取现有文件并将数据转换为 TypeScript 对象:
import * as ExcelJS from 'exceljs';
interface Employee { id: number; name: string; position: string; salary: number;}
async function readWorkbook() { const workbook = new ExcelJS.Workbook(); await workbook.xlsx.readFile('employees.xlsx'); const sheet = workbook.getWorksheet('员工'); const employees: Employee[] = [];
sheet.eachRow((row, rowNumber) => { if (rowNumber === 1) return; // 跳过标题行 employees.push({ id: row.getCell(1).value as number, name: row.getCell(2).value as string, position: row.getCell(3).value as string, salary: row.getCell(4).value as number, }); });
console.log('读取到的员工数量:', employees.length); console.log(employees);}
readWorkbook();格式与样式
ExcelJS 允许自定义单元格的外观:字体、填充、边框、对齐方式。为标题添加样式的示例:
import * as ExcelJS from 'exceljs';
async function styledWorkbook() { const workbook = new ExcelJS.Workbook(); const sheet = workbook.addWorksheet('报告');
// 定义标题样式 const headerStyle: Partial&