当前位置: 首页 > java >正文

js中的FileReader对象

一个简单的例子来理解:
读取用户上传的 Excel 文件(.xlsx),解析内容,并以表格形式在页面上显示出来。

它依赖一个外部库:XLSX.js(即 SheetJS),用于解析 Excel 数据。

代码

index.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><h2>上传Excel文件</h2><input type="file" name="" id="excelFile" accept=".xlsx, .xls"><div id="output"></div><script src="https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js"></script><script src="index.js"></script>
</body>
</html>

index.js

// 读取excel并提取列内容
const UploadFie = document.querySelector("#excelFile")UploadFie.addEventListener("change", handleFile)function handleFile(event) {const file = event.target.files[0]// console.log(event.target.files[0])// const reader = new FileReader()reader.onload = function(e) {const data =  new Uint8Array(e.target.result)const workbook = XLSX.read(data, {type: "array"})const firstSheetName = workbook.SheetNames[0]const worksheet = workbook.Sheets[firstSheetName]// 转为 json 格式const jsonData = XLSX.utils.sheet_to_json(worksheet)// 渲染结果renderTable(jsonData)}// reader.readAsArrayBuffer(file)
}function renderTable(data) {const output = document.querySelector("#output")output.innerHTML = ""if (data.length === 0) {output.textContent = "没有数据"return}const table = document.createElement("table")table.style.border = "1"const thead = table.insertRow()Object.keys(data[0]).forEach(key => {const th = document.createElement("th")th.textContent = keythead.appendChild(th)})data.forEach(row => {const tr = table.insertRow()Object.values(row).forEach(value => {const td = tr.insertCell()td.textContent = value})})output.appendChild(table)
}

带注释js代码

// 获取页面上 ID 为 "excelFile" 的 <input type="file"> 元素,用于文件上传
const UploadFie = document.querySelector("#excelFile");// 给文件上传输入框添加事件监听器,监听 "change" 事件(用户选中文件时触发)
UploadFie.addEventListener("change", handleFile);// 文件选择后的处理函数
function handleFile(event) {// 获取用户选择的第一个文件对象(如果选择多个,只取第一个)const file = event.target.files[0];// 创建一个 FileReader 实例,用于读取文件内容const reader = new FileReader();// 当文件读取完成后触发 onload 回调函数reader.onload = function(e) {// 将读取到的 ArrayBuffer 包装成 Uint8Array 类型的字节数组const data = new Uint8Array(e.target.result);// 使用 SheetJS (XLSX) 读取 Excel 文件内容,指定类型为 "array"const workbook = XLSX.read(data, { type: "array" });// 获取 Excel 的第一个工作表名称const firstSheetName = workbook.SheetNames[0];// 获取第一个工作表对象const worksheet = workbook.Sheets[firstSheetName];// 将工作表数据转换为 JSON 格式数组,每一行为一个对象const jsonData = XLSX.utils.sheet_to_json(worksheet);// 将数据渲染为 HTML 表格并显示在页面上renderTable(jsonData);};// 将文件内容以 ArrayBuffer(二进制缓冲区)方式读取(适用于 Excel)reader.readAsArrayBuffer(file);
}// 渲染 JSON 数据为 HTML 表格,并插入到页面中
function renderTable(data) {// 获取用于显示表格的容器(一般是一个 <div id="output">)const output = document.querySelector("#output");// 清空上一次渲染的内容output.innerHTML = "";// 如果数据为空,显示提示文字并结束函数if (data.length === 0) {output.textContent = "没有数据";return;}// 创建一个新的 HTML 表格元素const table = document.createElement("table");table.style.border = "1"; // 设置表格边框(简易做法)// 创建表头(thead),使用数据的键(字段名)作为列名const thead = table.insertRow(); // 插入第一行作为表头Object.keys(data[0]).forEach(key => {const th = document.createElement("th"); // 创建表头单元格th.textContent = key; // 设置列名(字段名)thead.appendChild(th); // 将表头单元格添加到表头行中});// 遍历数据数组,为每一行数据创建表格行data.forEach(row => {const tr = table.insertRow(); // 创建新行Object.values(row).forEach(value => {const td = tr.insertCell(); // 创建单元格td.textContent = value;     // 填入单元格的值});});// 将完整表格添加到页面上的容器中output.appendChild(table);
}

结构总览 & 难理解的点

代码分为三大部分:

  1. 监听文件上传:UploadFie.addEventListener(...)
  2. 处理上传的文件内容并解析 Excel:handleFile 函数
  3. 将数据渲染成 HTML 表格:renderTable 函数

const data = new Uint8Array(e.target.result);

解释:
上面代码中:reader.readAsArrayBuffer(file); 我们通过 FileReaderreadAsArrayBuffer() 方法来读取文件内容,读取完成后触发 reader.onload,其事件对象 e 中包含的 e.target.result 是一个 ArrayBuffer

ArrayBuffer 是一种原始的、通用的二进制数据容器,不能直接读取内容,需要借助视图(如 Uint8Array, DataView, Float32Array 等)进行解析。


Uint8Array()

  • Uint8Array 是 JavaScript 中的一种类型化数组(TypedArray)
  • 它提供了对 ArrayBuffer 的结构化、字节级别的访问

const workbook = XLSX.read(data, { type: "array" });

  • XLSX.read() 要求的是字节数组
  • SheetJSXLSX.read() 方法如果传入 {type: "array"},它期望的输入是一个 Uint8Array,因此我们必须将原始的 ArrayBuffer 包装为 Uint8Array,否则 XLSX.read() 无法解析

🔬 ArrayBuffer VS Uint8Array

  • ArrayBuffer 就像一块原始磁盘空间,你知道有数据,但无法读取。
  • Uint8Array 就像一个读卡器,它能以 8 位为单位读出这些数据。

http://www.xdnf.cn/news/14800.html

相关文章:

  • 指针篇(7)- 指针运算笔试题(阿里巴巴)
  • 计算机科学导论(1)哈佛架构
  • 高功率的照明LN2系列助力电子元件薄膜片检测
  • 二叉树题解——验证二叉搜索树【LeetCode】后序遍历
  • 【狂飙AGI】第8课:AGI-行业大模型(系列2)
  • LangChain 全面入门
  • [ctfshow web入门] web94 `==`特性与intval特性
  • 【Python小工具】使用 OpenCV 获取视频时长的详细指南
  • 【Note】《深入理解Linux内核》Chapter 9 :深入理解 Linux 内核中的进程地址空间管理机制
  • FASTAPI+VUE3平价商贸管理系统
  • MySQL数据库----DML语句
  • 论文阅读笔记——Autoregressive Image Generation without Vector Quantization
  • uniapp打包微信小程序主包过大问题_uniapp 微信小程序时主包太大和vendor.js过大
  • 深度学习-逻辑回归
  • 深入理解 Redis Cluster:分片、主从与脑裂
  • Gemini CLI初体验
  • MySQL 8.0 OCP 1Z0-908 题目解析(17)
  • SciPy 安装使用教程
  • 数据结构:数组在编译器中的表示(Array Representation by Compiler)
  • NumPy-核心函数transpose()深度解析
  • MediaCrawler:强大的自媒体平台爬虫工具
  • 【python】OOP:Object-Oriented Programming
  • DHCP中继及动态分配
  • 全双工和半双工在以太网报文收发过程中的核心区别
  • 读书笔记:《DevOps实践指南》
  • GitHub 解码指南:用 AI 赋能,五步快速掌握任意开源项目
  • IOC容器讲解以及Spring依赖注入最佳实践全解析
  • LeetCode--40.组合总和II
  • Android App冷启动流程详解
  • 基于 Elasticsearch 实现地图点聚合