excel流文件的前端展示(显示表格)

安装和引入xlsx依赖包
npm install -S xlsx
import XLSX from 'xlsx'

excel流文件的前端展示(显示表格)_第1张图片

excel表格显示

>
//不需要分页的话 这段和上面 "tableData.slice..." 直接换成tableData即可
import XLSX from 'xlsx'
import axios from 'axios'
export default {
  data() {
    return {
      currpage:1,
      pagesize:20,
      totalNum:0, 
      tableData: [],
      card: [], // excel表格sheet的数组
      cardActive: '', // excel表格当前显示的sheet
      workbook: {},
    };
  },
  mounted () {
    this.showStandard('Doc/code.xlsx');  //通过服务器获取流
    // this.readFile('code.xlsx')  //获取前端public下的excel文件
  },
}

获取excel的流文件

因为后台获取文件流是 .net core异步获取,所以这里用async 和 await 处理
// 获取后台的流文件
async showStandard(excelUrl){
        var type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        var filePaths = []
        filePaths.push(excelUrl)
        let res = await this.$axios.post("/api/Base/DownFileZip",filePaths,{ responseType: 'arraybuffer' })
        var data = new Uint8Array(res)
        var workbook = XLSX.read(data, {type:"array"})
        var sheetNames = workbook.SheetNames // 工作表名称集合
        this.workbook = workbook
        this.card = sheetNames
        this.cardActive = sheetNames[0]
        this.getTable(sheetNames[0])
},
// 获取前端的流文件
readFile(url) {
        axios.get(url, {responseType:'arraybuffer'}).then((res) => {
            var data = new Uint8Array(res)
            var workbook = XLSX.read(data, {type:"array"})
            var sheetNames = workbook.SheetNames // 工作表名称集合
            this.workbook = workbook
            this.card = sheetNames
            this.cardActive = sheetNames[0]
            this.getTable(sheetNames[0])
        })
    },
getTable (sheetName) {
        this.Matches = []
        this.currpage = 1
        var worksheet = this.workbook.Sheets[sheetName]
        this.tableData = XLSX.utils.sheet_to_json(worksheet)
        //获取第一行(即表头)
        var header = XLSX.utils.sheet_to_json(worksheet,{header:1})[0]
        var tableTitle = this.tableData[0]
        var table0 = {}
        //这里对表头进行处理,因为获取的数据渲染表头是根据第一条数据,
        //当excel文件中第一条数据有为空时,第一条数据没有此属性,数据就不渲染,所以把为空的属性设置成“”
        for(var i=0;i

设置表格样式

//给表头添加标识
renderHeader(h,{column,$index}){
  return h(
         'div',{style:'width:100%'},[
               h('span', column.label),
               h('span', {
                   class: "floatCR",
                   style:'color:#0094CE;margin-left:15px;font-family:Eurostile Bold'
                   },1==$index?'C':(3==$index?'R':''))
          ],
       );
},
//给列设置背景色
columnStyle({ row, column, rowIndex, columnIndex }) {
  if (columnIndex ==1||columnIndex ==3) 
  {
    return 'background:rgba(147, 195, 235,0.05);'
  }
},

表格分页

handleSizeChange(val) {
  this.pagesize = val
},
handleCurrentChange(val) {
  this.currpage = val
},

第一次写,就是想记录一下,有不规范的地方还请各位大哥赐教,谢谢!

你可能感兴趣的:(vue.js前端)