一、展示word文件内容
1、安装并引入依赖mammoth
npm install --save mammoth
import mammoth from "mammoth"
2、页面中使用
<div style="height:850px;overflow-y:auto;" v-html="content"/>
//根据文件url,以arraybuffer的形式获取docx文件内容,传给插件转成html格式,展示在页面上
var xhr = new XMLHttpRequest()
xhr.open('GET', fileurl, true)
xhr.responseType = 'arraybuffer'
const rhis = this
xhr.onload = function(){
if(xhr.status === 200){
mammoth.convertToHtml({arrayBuffer: new Uint8Array(xhr.response)}).then(function(res){
rhis.$nextTick(()=>{
rhis.content = res.value
})
})
}
}
xhr.send()
二、展示excel/csv文件内容
1、安装并引入依赖handsontable、papaparse,excel文件需要安装xlxs
npm install handsontable @handsontable/vue
npm install papaparse
npm install xlsx
import Papa from 'papaparse'
import xlsx from 'xlsx'
2、公共组件sheet.vue
<template>
<div class="overf">
<div id="table" class="sheet">
<hot-table ref="hot" :data="data" :settings="hotSettings" />
</div>
</div>
</template>
<script>
import { HotTable } from '@handsontable/vue'
// import Handsontable from 'handsontable'
import 'handsontable/dist/handsontable.full.css'
export default {
components: { HotTable },
props: {
data: {
type: Array,
default() {
return []
}
}
},
data() {
return {
hot: null,
hotSettings: {
readOnly: true
// manualColumnResize: true,
// manualRowResize: true,
// minSpareRows: 0
}
}
},
watch: {
data(newValue) {
this.$refs.hot.hotInstance.loadData(newValue)
}
},
created() {
},
methods: {}
}
</script>
<style lang="scss" scoped>
.overf{
height: 300px;
overflow: hidden;
}
.sheet{
height: 100%;overflow: auto;
&>>>#hot-display-license-info{
display:none;
}
}
</style>
3、页面内引入组件
import sheet from './sheet'
<sheet v-if="isCsv" :data="sheetData" />
data() {
return {
sheetData: [], // sheet
}
},
// csv文件
this.sheetData = []
const rhis = this
Papa.parse(fileurl, {
download: true,
complete: res => {
const arrs = res.data
const lastItem = arrs[arrs.length - 1].every(val => val === '')
lastItem && arrs.pop()
rhis.sheetData = arrs
rhis.isCsv = true
}
})
// excel文件
var xhr2 = new XMLHttpRequest()
xhr2.open('GET', fileurl, true)
xhr2.responseType = 'blob'
const rhis = this
xhr2.onload = function() {
var blob = this.response
var reader = new FileReader()
reader.onload = function(e) {
const wb = xlsx.read(e.target.result, {
type: 'binary'
})
rhis.outputWorkbook(wb) // 处理数据
}
reader.readAsBinaryString(blob)
}
xhr2.send()
// 读取 excel 文件
outputWorkbook(workbook) {
this.sheetData = []
var sheetNames = workbook.SheetNames // 工作表名称集合
sheetNames.forEach(name => {
var worksheet = workbook.Sheets[name] // 只能通过工作表名称来获取指定工作表
var data = xlsx.utils.sheet_to_csv(worksheet)
Papa.parse(data, { // 使用papaparse解析csv数据,并展示在表格中
complete: res => {
const arrs = res.data
// 去除最后的空行
const lastItem = arrs[arrs.length - 1].every(val => val === '')
lastItem && arrs.pop()
this.sheetData = arrs
this.isCsv = true
}
})
})
},