一、展示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
}
})
})
},
总结
到此这篇关于如何利用vue展示.docx文件、excel文件和csv文件内容的文章就介绍到这了,更多相关vue展示docx、excel和csv文件内容内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!