JavaScript如何讀取本地excel文件、txt文件的內(nèi)容
<input type="file" @change="fileChange">
1、txt文件
fileChange(event) {
console.log('fileChange', event)
const file = event.target.files[0];
const reader = new FileReader();
reader.readAsText(file);
reader.onload = function(e) {
console.log('reader', e)
// 文本內(nèi)容
console.error(reader.result)
// 切分行
// reader.result.split('\n').forEach(function(v, i){
// console.log(v);
// });
};
}2、excel文件
1)安裝解析插件xlsx
npm i xlsx
2)以 array 形式讀取
import * as XLSX from 'xlsx'
fileChange(event) {
console.log('fileChange', event)
const file = event.target.files[0];
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function(e) {
console.log('reader', e)
// excel文件 —— array
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, {type: 'array'});
// 假設(shè)我們只讀取第一個(gè)工作表
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet);
console.log(jsonData, worksheet);
};
}3)以 binary 形式讀取
import * as XLSX from 'xlsx'
fileChange(event) {
console.log('fileChange', event)
const file = event.target.files[0];
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function(e) {
console.log('reader', e)
// excel文件 —— binary
const workbook = XLSX.read(e.target.result, {type: 'binary'});
const sheetNames = workbook.SheetNames; // 工作表名稱集合
const worksheet = workbook.Sheets[sheetNames[0]]; // 這里我們只讀取第一張sheet
// 輸出字符串形式
const csv = XLSX.utils.sheet_to_csv(worksheet);
console.log(csv)
// 輸出數(shù)組形式
const rows = csv.split('\n'); // 轉(zhuǎn)化為數(shù)組
rows.pop(); // 最后一行沒用的
console.log(rows); // 打印輸出的數(shù)組
};
}3、vue案例
1)組件形式
一個(gè)可以解析獲取本地excel文件和txt文件的按鈕組件,可以自定義插槽內(nèi)容
<parseExcelBtn @getResult="getResult"></parseExcelBtn>
<parseExcelBtn @getResult="getResult" btnWidth="300px">
<span>自定義按鈕</span>
</parseExcelBtn>
getResult(e) {
console.log(e)
},<template>
<div class="parse-excel-btn"
:style="{
width: btnWidth
}"
@click="doClick">
<slot v-if="hasDefaultSlotContent"></slot>
<div v-else class="txt">{{ btnTxt }}</div>
<input type="file" hidden accept=".txt, .xlsx, .xls" ref="fileInput" @change="fileChange">
</div>
</template>
<script lang="ts" setup>
import { ref, withDefaults, defineProps, defineEmits, watch, useSlots, onMounted } from 'vue'
import * as XLSX from 'xlsx'
import { Message } from 'view-ui-plus'
interface Props {
btnTxt?: string, // 按鈕文本
btnWidth?: string // 按鈕寬度
resultType?: string // 輸出結(jié)果類型
readType?: string // 讀取類型
}
const props = withDefaults(defineProps<Props>(), {
btnTxt: '導(dǎo)入excel',
btnWidth: 'auto',
resultType: 'string', // array string
readType: 'binary' // array binary
})
console.log(props)
const emit = defineEmits(['getResult'])
const fileInput = ref(null)
const hasDefaultSlotContent = ref(false)
const slots = useSlots();
onMounted(() => {
// 檢查默認(rèn)插槽是否有內(nèi)容
if (slots.default) {
const slotContent = slots.default();
if(slotContent) {
hasDefaultSlotContent.value = true
}
// hasDefaultSlotContent.value = slotContent.some(({ vnode }) => {
// console.log(vnode)
// // 檢查節(jié)點(diǎn)是否是文本節(jié)點(diǎn)且不為空
// return vnode.type === Text && vnode.children.trim() !== '';
// });
}
})
// 按鈕點(diǎn)擊
function doClick() {
if(fileInput) {
fileInput.value.click()
}
}
// 本地文件選擇
function fileChange(event: any) {
console.log('fileChange', event)
const file = event.target.files[0];
if(!file) {
return
}
let testMsg = file.name.substring(file.name.lastIndexOf('.')+1)
if(!['txt','xlsx', 'xls'].includes(testMsg)) {
Message.error('不是excel文件~')
return
}
const reader = new FileReader();
if(testMsg === 'txt') {
reader.readAsText(file);
} else {
if(props.readType === 'array'){
reader.readAsArrayBuffer(file);
} else {
reader.readAsBinaryString(file);
}
}
reader.onload = function(e) {
// console.log('reader', e)
if(testMsg === 'txt') {
// txt文件
// console.error(reader.result)
// reader.result.split('\n').forEach(function(v, i){
// console.log(v);
// });
emit('getResult', reader.result)
} else {
if(props.readType === 'array') {
// excel文件 —— array
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, {type: 'array'});
// 假設(shè)我們只讀取第一個(gè)工作表
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet);
// console.log(jsonData, worksheet);
emit('getResult', jsonData)
} else {
// excel文件 —— binary
const workbook = XLSX.read(e.target.result, {type: 'binary'});
const sheetNames = workbook.SheetNames; // 工作表名稱集合
const worksheet = workbook.Sheets[sheetNames[0]]; // 這里我們只讀取第一張sheet
const csv = XLSX.utils.sheet_to_csv(worksheet);
if(props.resultType === 'array') {
// 數(shù)組形式
const rows = csv.split('\n'); // 轉(zhuǎn)化為數(shù)組
rows.pop(); // 最后一行沒用的
// console.log(rows); // 打印輸出的數(shù)組
emit('getResult', rows)
} else {
// 字符串形式
// console.log(csv)
emit('getResult', csv)
}
}
}
}
}
</script>
<style lang="scss" scoped>
.parse-excel-btn {
cursor: pointer;
.txt {
line-height:40px;
background:#ebf2ff;
border-radius:6px;
text-align: center;
font-weight:500;
color:#0055ff;
font-size:16px;
}
}
</style>2)函數(shù)調(diào)用形式
<button @click="handleParseExcel">excel</button>
mounted() {
this.doParseExcel = parseExcel({
// resultType?: string,
// readType?: string
}, this.parseExcelCallBack)
},
methods: {
// 回調(diào)
parseExcelCallBack(e) {
console.log(e)
},
// 導(dǎo)入
handleParseExcel() {
this.doParseExcel()
},
}import * as XLSX from 'xlsx'
import { Message } from 'view-ui-plus'
export function parseExcel(props, fn) {
console.log('init parseExcel function')
const inputDom = document.createElement('input')
inputDom.type = 'file'
inputDom.accept = '.txt, .xlsx, .xls'
inputDom.addEventListener('change', fileChange)
// 本地文件選擇
function fileChange(event) {
console.log('fileChange', event, event.target, event.target.value)
const file = event.target.files[0];
if(!file) {
return
}
let testMsg = file.name.substring(file.name.lastIndexOf('.')+1)
if(!['txt','xlsx', 'xls'].includes(testMsg)) {
Message.error('不是excel文件~')
// event.target.value = ''
return
}
const reader = new FileReader();
if(testMsg === 'txt') {
reader.readAsText(file);
} else {
if(props.readType === 'array'){
reader.readAsArrayBuffer(file);
} else {
reader.readAsBinaryString(file);
}
}
reader.onload = function(e) {
// console.log('reader', e)
if(testMsg === 'txt') {
// txt文件
// console.error(reader.result)
// reader.result.split('\n').forEach(function(v, i){
// console.log(v);
// });
fn(reader.result)
} else {
if(props.readType === 'array') {
// excel文件 —— array
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, {type: 'array'});
// 假設(shè)我們只讀取第一個(gè)工作表
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet);
// console.log(jsonData, worksheet);
fn(jsonData)
} else {
// excel文件 —— binary
const workbook = XLSX.read(e.target.result, {type: 'binary'});
const sheetNames = workbook.SheetNames; // 工作表名稱集合
const worksheet = workbook.Sheets[sheetNames[0]]; // 這里我們只讀取第一張sheet
const csv = XLSX.utils.sheet_to_csv(worksheet);
if(props.resultType === 'array') {
// 數(shù)組形式
const rows = csv.split('\n'); // 轉(zhuǎn)化為數(shù)組
rows.pop(); // 最后一行沒用的
// console.log(rows); // 打印輸出的數(shù)組
fn(rows)
} else {
// 字符串形式
// console.log(csv)
fn(csv)
}
}
}
inputDom.value = ''
}
reader.onerror = function(e) {
Message.error(e)
console.log(e)
inputDom.value = ''
}
}
return () => {
if(inputDom) {
inputDom.click()
}
}
}總結(jié)
到此這篇關(guān)于JavaScript如何讀取本地excel文件、txt文件內(nèi)容的文章就介紹到這了,更多相關(guān)js讀取本地文件內(nèi)容內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript如何攔截全局Fetch的請(qǐng)求與響應(yīng)詳解
全局的fetch()方法用于發(fā)起獲取資源的請(qǐng)求,它返回一個(gè)promise,這個(gè)promise會(huì)在請(qǐng)求響應(yīng)后被resolve,并傳回Response對(duì)象,這篇文章主要給大家介紹了關(guān)于JavaScript如何攔截全局Fetch的請(qǐng)求與響應(yīng)的相關(guān)資料,需要的朋友可以參考下2024-04-04
用javascript獲取textarea中的光標(biāo)位置
Javascript一向以他的靈活隨意而著稱,這也使得它的功能可以非常的強(qiáng)大,而由于沒有比較好的調(diào)試工具,又使得它使用起來困難重重,尤其使對(duì)于一些初學(xué)者,更是感覺到無從下手。今天探討的問題是用javascript獲取textarea中光標(biāo)的位置。2008-05-05
JavaScript中5種調(diào)用函數(shù)的方法
這篇文章主要介紹了JavaScript中5種調(diào)用函數(shù)的方法,本文詳細(xì)的介紹了Javascript中各種函數(shù)調(diào)用的方法及其原理,對(duì)于理解JavaScript的函數(shù)有很大的幫助,需要的朋友可以參考下2015-03-03
JavaScript實(shí)現(xiàn)刷新不重記的倒計(jì)時(shí)
網(wǎng)上關(guān)于JavaScript實(shí)現(xiàn)倒計(jì)時(shí)的文章有很多,但是一般都是刷新后會(huì)重新開始計(jì)時(shí),可是我們有的時(shí)候會(huì)需要刷新卻不重新計(jì)算的倒計(jì)時(shí),這該怎么做呢?下面我們一起來看看這種倒計(jì)時(shí)怎么實(shí)現(xiàn)吧。2016-08-08
JavaScript實(shí)現(xiàn)創(chuàng)建自定義對(duì)象的常用方式總結(jié)
這篇文章主要介紹了JavaScript實(shí)現(xiàn)創(chuàng)建自定義對(duì)象的常用方式,結(jié)合實(shí)例形式總結(jié)分析了JavaScript工廠模式、構(gòu)造函數(shù)模式、原型模式、組合模式等常用的自定義對(duì)象創(chuàng)建模式操作與使用技巧,需要的朋友可以參考下2018-07-07
javaScript實(shí)現(xiàn)鼠標(biāo)在文字上懸浮時(shí)彈出懸浮層效果
這篇文章主要為大家詳細(xì)介紹了javaScript實(shí)現(xiàn)鼠標(biāo)在文字上懸浮時(shí)彈出懸浮層效果的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03
關(guān)于js中window.location.href,location.href,parent.location.href
關(guān)于js中window.location.href,location.href,parent.location.href,top.location.href的用法2010-10-10

