目录
- 前言
- excel 表格文件到底是什么
- JS 实现步骤
- ZIP 解压
- XML 解析
- 总结
前言
今天来聊一聊如何使用 JS 来解析 excel 文件,当然不是直接使用 exceljs、sheetjs 之类的库,那就没意思了,而是主要说一下 JS 解析 excel 表格是如何实现的。
注意本文主要讨论 xlsx 格式的 excel 表格,其它格式未探究并不清楚。
excel 表格文件到底是什么
首先要解析 excel 文件,得先了解他是如何存储数据的,经过我百般搜索,终于在 GG 中找到了答案:excel 文件其实是一个 zip 包!于是我赶紧新建了一个 xlsx 文件,在其中新建了两个 sheet 表,两个 sheet 表数据如下:
此为 sheet 1:
此为 sheet 2:
然后使用 zip 进行解压:
unzip test.xlsx -d test
然后通过 tree 我们就拿到这样一个目录结构:
test
├── [Content_Types].xml
├── _rels
├── docProps
│ ├── app.xml
│ ├── core.xml
│ └── custom.xml
└── xl
├── _rels
│ └── workbook.xml.rels
├── sharedStrings.xml
├── styles.xml
├── theme
│ └── theme1.xml
├── workbook.xml
└── worksheets
├── sheet1.xml
└── sheet2.xml
啊哈,干得漂亮,居然全都是 xml 文件。
我们在打开 xml 一探究竟,可以看出有几个文件很显眼,就是 worksheets 下的 sheet1.xml 和 sheet2.xml,还有 workbook.xml,其他的 styles、theme 一看就是和样式有关系,_rels 感觉就是什么内部引用,我们先看看两个 sheet 的 xml 文件,看看猜测是否正确,贴下 sheet1.xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"
xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:etc="http://www.wps.cn/officeDocument/2017/etCustomData">
<sheetPr/>
<dimension ref="A1:C7"/>
<sheetViews>
<sheetView workbookViewId="0">
<selection activeCell="D5" sqref="A3:D5"/>
</sheetView>
</sheetViews>
<sheetFormatPr defaultColWidth="9.23076923076923" defaultRowHeight="16.8" outlineLevelRow="6" outlineLevelCol="2"/>
<sheetData>
<row r="1" spans="1:3">
<c r="A1">
<v>1</v>
</c>
<c r="C1">
<v>2</v>
</c>
</row>
<row r="2" spans="1:3">
<c r="A2">
<v>1</v>
</c>
<c r="C2">
<v>2</v>
</c>
</row>
<row r="6" spans="1:3">
<c r="A6">
<v>1</v>
</c>
<c r="C6">
<v>2</v>
</c>
</row>
<row r="7" spans="1:3">
<c r="A7">
<v>1</v>
</c>
<c r="C7">
<v>2</v>
</c>
</row>
</sheetData>
<pageMargins left="0.75" right="0.75" top="1" bottom="1" header="0.5" footer="0.5"/>
<headerFooter/>
</worksheet>
