<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)
// 文本内容
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'});
// 假设我们只读取第一个工作表
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)
// 输出数组形式
const rows = csv.split('\n'); // 转化为数组
rows.pop(); // 最后一行没用的
console.log(rows); // 打印输出的数组
};
}3、vue案例
1)组件形式
一个可以解析获取本地excel文件和txt文件的按钮组件,可以自定义插槽内容
<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 // 输出结果类型
readtype?: string // 读取类型
}
const props = withdefaults(defineprops<props>(), {
btntxt: '导入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(() => {
// 检查默认插槽是否有内容
if (slots.default) {
const slotcontent = slots.default();
if(slotcontent) {
hasdefaultslotcontent.value = true
}
// hasdefaultslotcontent.value = slotcontent.some(({ vnode }) => {
// console.log(vnode)
// // 检查节点是否是文本节点且不为空
// return vnode.type === text && vnode.children.trim() !== '';
// });
}
})
// 按钮点击
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'});
// 假设我们只读取第一个工作表
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') {
// 数组形式
const rows = csv.split('\n'); // 转化为数组
rows.pop(); // 最后一行没用的
// console.log(rows); // 打印输出的数组
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)函数调用形式
<button @click="handleparseexcel">excel</button>
mounted() {
this.doparseexcel = parseexcel({
// resulttype?: string,
// readtype?: string
}, this.parseexcelcallback)
},
methods: {
// 回调
parseexcelcallback(e) {
console.log(e)
},
// 导入
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'});
// 假设我们只读取第一个工作表
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') {
// 数组形式
const rows = csv.split('\n'); // 转化为数组
rows.pop(); // 最后一行没用的
// console.log(rows); // 打印输出的数组
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()
}
}
}总结
到此这篇关于javascript如何读取本地excel文件、txt文件内容的文章就介绍到这了,更多相关js读取本地文件内容内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论