您的当前位置:首页正文

前端用vue写文件预览txt,pdf,doc|| docx,xls || xlsx 等格式文件

2024-11-30 来源:个人技术集锦

引入

import mammoth from 'mammoth'
import XLSX from 'xlsx'

html


   <el-dialog fullscreen :visible.sync="previewDialogVisible">
      <iframe v-if="pdfContent.length > 0" :src="pdfContent" width="100%" :height="HIfram" frameborder="0" />
      <div v-if="txtContent.length > 0" v-html="txtContent" />
      <div v-if="wordContent.length > 0" v-html="wordContent" />
      <el-table v-if="excelContent.header.length > 0" :data="excelContent.results" border highlight-current-row style="width: 100%">
        <el-table-column v-for="item in excelContent.header" :key="item + Math.random()" :prop="item" :label="item" />
      </el-table>
    </el-dialog>

js

***我在网上扒了方便pdf演示的html ***
pdfContent:http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf
来自

data(){

	return {
		 previewDialogVisible: false,
	      txtContent: '',
	      pdfContent: 'http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf', // pdf地址',
	      wordContent: '',
	      excelContent: {
	        header: [],
	        results: []
	      },
	}
}

yulanDownload (row) {
        //调接口 后端返回文件流
        downloadFile(row.originalFilename, row.url).then(response => {
	    	//----此操作是截取文件名后缀判断格式
            const suffix = row.originalFilename.substring(row.originalFilename.toLowerCase().lastIndexOf('.') + 1)
            
            if (suffix === 'txt') {
              this.wordContent = ''
              this.pdfContent = ''
              this.excelContent = { header: [], results: [] }
              const that = this
              var reader = new FileReader()
              reader.readAsText(response)
              reader.onload = function (event) {
                that.txtContent = reader.result
              }
              this.previewDialogVisible = true
            } else if (suffix === 'pdf') {
              this.txtContent = ''
              this.wordContent = ''
              this.excelContent = { header: [], results: [] }
              const blob = new Blob([response], { type: 'application/pdf' })
              const fileURL = URL.createObjectURL(blob)
              const url = encodeURIComponent(fileURL)
              this.pdfContent = `/static/pdf/web/viewer.html?file=${url}`
              this.previewDialogVisible = true
            } else if (suffix === 'doc' || suffix === 'docx') {
              this.txtContent = ''
              this.pdfContent = ''
              this.excelContent = { header: [], results: [] }
              const that = this
              var file = response
              var reader = new FileReader()
              reader.readAsArrayBuffer(file)
              reader.onload = function (e) {
                const buffer = e.target.result
                mammoth.convertToHtml({ arrayBuffer: buffer }).then((result) => {
                  that.wordContent = result.value
                }).done()
              }
              this.previewDialogVisible = true
            } else if (suffix === 'xls' || suffix === 'xlsx') {
              this.txtContent = ''
              this.wordContent = ''
              this.pdfContent = ''
              this.readerData(response)
              this.previewDialogVisible = true
            }
        })
    
      }
    },


 readerData (rawFile) {


      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        console.log("___", reader)
        reader.onload = e => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const header = this.getHeaderRow(worksheet)
          const results = XLSX.utils.sheet_to_json(worksheet, { defval: '' })
          this.generateData({ header, results })
          resolve()
        }
        reader.readAsArrayBuffer(rawFile)
      })
    },
  generateData ({ header, results }) {
      this.excelContent.header = header
      this.excelContent.results = results
    },
 getHeaderRow (sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        // let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        let hdr = ' '
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },

预览

我只附上了pdf的截图 其他的比较简单 不说了

显示全文