功能:上传word文档后,获取文档中的文字数据
需要安装 mammoth 和 docx-preview
<template>
<el-button type="primary" class="btn" @click="uploadFile">上传word文件</el-button>
</template>
<script setup lang="ts">
import mammoth from 'mammoth'
import { renderAsync } from 'docx-preview'
const uploadFile = () => {
let inputEle = document.createElement('input')
inputEle.type = 'file'
inputEle.accept =
'.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document'
inputEle.click()
inputEle.addEventListener('input', (event) => {
onWord(event)
})
}
const onWord = (event) => {
let reader = new FileReader()
let file = event.target.files[0]
let options = { inWrapper: false, ignoreWidth: true, ignoreHeight: true }
renderAsync(file, document.getElementById('preview'), null, options)
if (file) {
reader.onload = function (e) {
const data = e.target!.result
const options: any = {
arrayBuffer: data
}
// 转文字
mammoth
.extractRawText(options)
.then(function (displayResult) {
parse(displayResult.value)
console.log('解析结果', displayResult)
})
.done()
// 转HTML
mammoth
.convertToHtml(options)
.then(function (displayResult) {
console.log('转HTML', displayResult)
})
.done()
// 转Markdown 文档。
mammoth
.convertToMarkdown(options)
.then(function (displayResult) {
console.log('转Markdown 文档', displayResult)
})
.done()
}
reader.readAsArrayBuffer(file)
}
}