Front-end uploading excel file and read the data in the file

1, read data uploaded to achieve pure js file and display

github can download the file locally run
Demo

Read local files

$(function() {
		document.getElementById('file').addEventListener('change', function(e) {
			var files = e.target.files;
			console.log(files)
			if(files.length == 0) return;
			var f = files[0];
			console.log(f)
			if(!/\.xlsx$/g.test(f.name)) {
				alert('仅支持读取xlsx格式!');
				return;
			}
			readWorkbookFromLocalFile(f, function(workbook) {
				readWorkbook(workbook);
			});
		});
		// loadRemoteFile('./sample/test.xlsx');
	});
	
 // 读取本地excel文件
    function readWorkbookFromLocalFile(file, callback) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var data = e.target.result;
            var workbook = XLSX.read(data, {type: 'binary'});
            if(callback) callback(workbook);
        };
        reader.readAsBinaryString(file);
    }
 function readWorkbook(workbook) {
        var sheetNames = workbook.SheetNames; // 工作表名称集合
        var worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet
        var csv = XLSX.utils.sheet_to_csv(worksheet);
        document.getElementById('result').innerHTML = csv2table(csv);
    }

workbook is the data we need
Here Insert Picture Description

2, vuejs achieve excel upload and read

installation

cnpm install xlsx --save

Code:

<template>
  <span>
    <input class="input-file" type="file" @change="exportData"
           accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
    <button @click="btnClick">导入EXCEL</button>
  </span>
</template>

<script>
import XLSX from 'xlsx'

export default {
  name: 'HelloWorld',
  props: {
    type: String,
    default: '选择excel文件'
  },
  methods: {
    btnClick () {
      document.querySelector('.input-file').click()
    },
    exportData (event) {
      if (!event.currentTarget.files.length) {
        return
      }
      const that = this
      // 拿取文件对象
      var f = event.currentTarget.files[0]
      // 用FileReader来读取
      var reader = new FileReader()
      // 重写FileReader上的readAsBinaryString方法
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = ''
        var wb // 读取完成的数据
        var outdata // 你需要的数据
        var reader = new FileReader()
        reader.onload = function (e) {
          // 读取成Uint8Array,再转换为Unicode编码(Unicode占两个字节)
          var bytes = new Uint8Array(reader.result)
          var length = bytes.byteLength
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i])
          }
          // 接下来就是xlsx了,具体可看api
          wb = XLSX.read(binary, {
            type: 'binary'
          })
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
          // 自定义方法向父组件传递数据
          console.log('outdata = ' + JSON.stringify(outdata))
          for(var i = 0;i<outdata.length;i++){
          console.log(outdta[i])
          }
          that.$emit('getResult', outdata)
        }
        reader.readAsArrayBuffer(f)
      }
      reader.readAsBinaryString(f)
    }
  }
}
</script>

<style scoped>
  .input-file {
    display: none;
  }
</style>
Published 42 original articles · won praise 4 · Views 6108

Guess you like

Origin blog.csdn.net/qq_43427385/article/details/102720130