# xlsx
Github 仓库地址 (opens new window)
xlsx
是一个流行的 npm 包,用于在 Node.js 应用程序中解析和写入各种电子表格格式(如 XLS, XLSX)。以下是如何入门使用 xlsx
包的基本指南:
# 安装
首先,你需要在你的项目中安装 xlsx
包。在你的项目根目录下,运行以下命令:
npm install xlsx
ok
1
# 读取电子表格
const XLSX = require('xlsx') // 读取文件 const workbook = XLSX.readFile('path/to/your/spreadsheet.xlsx') // 获取工作表的第一个工作表名称 const sheetName = workbook.SheetNames[0] // 获取工作表 const worksheet = workbook.Sheets[sheetName] // 将工作表转换为JSON对象 const data = XLSX.utils.sheet_to_json(worksheet) console.log(data)
ok
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 写入电子表格
const XLSX = require('xlsx') // 创建一个工作簿对象 const workbook = XLSX.utils.book_new() // 假设我们有以下JSON数据 const data = [ { name: 'John', city: 'Seattle' }, { name: 'Mike', city: 'Los Angeles' }, ] // 将JSON转换为工作表 const worksheet = XLSX.utils.json_to_sheet(data) // 将工作表添加到工作簿 XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1') // 写入文件 XLSX.writeFile(workbook, 'path/to/your/output/spreadsheet.xlsx')
ok
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 解析电子表格数据
const XLSX = require('xlsx') // 读取文件的二进制字符串 const file = XLSX.read(binaryString, { type: 'binary' }) // 解析数据...
ok
1
2
3
4
5
6
2
3
4
5
6
# 使用浏览器
如果你想在浏览器中使用 xlsx
,你可以通过以下方式:
<!-- 在HTML文件中引入xlsx.full.min.js --> <script src="https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js"></script> <script> // 使用XLSX对象 function handleFileSelect(evt) { const files = evt.target.files if (!files || files.length == 0) return const file = files[0] const reader = new FileReader() reader.onload = e => { const data = new Uint8Array(e.target.result) const workbook = XLSX.read(data, { type: 'array' }) // ... 使用 workbook 对象 } reader.readAsArrayBuffer(file) } document .getElementById('file-upload') .addEventListener('change', handleFileSelect, false) </script> <!-- 创建一个文件上传控件 --> <input type="file" id="file-upload" />
ok
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
以上是 xlsx
包的基本使用方法。你可以根据你的具体需求读取、修改和写入电子表格。更多高级用法和选项可以在 xlsx
的官方文档中找到:xlsx documentation (opens new window)。