Handsontable vue如何實現在線編輯excal


官網地址:https://handsontable.com/

1.實現效果

 

2.安裝

import { HotTable } from '@handsontable/vue'
import Handsontable from 'handsontable'
 
3.頁面引用
<template>
           <hot-table
                  ref="tableServer"
                  :data="hotSettings.dataList"                          // excal中的數據源
                  :context-menu="hotSettings.contextMenu"               // 右擊鼠標可進行的操作
                  :col-headers="hotSettings.colHeaders"                 // 表格頭部標題
                  :start-rows="hotSettings.startRows"                   // 默認固定行數
                  :start-cols="hotSettings.startCols"                   // 默認固定列數
                  :row-headers="hotSettings.rowHeaders"                 // 默認顯示表格行頭部
                  :row-heights="hotSettings.rowHeights"                 // 默認設置行高度
                  :manual-row-resize="hotSettings.manualRowResize"      // 
                  :manual-column-resize="hotSettings.manualColumnResize"
                  :manual-row-move="hotSettings.manualRowMove"
                  :columns="hotSettings.columns"
                  :before-remove-row="hotSettings.beforeRemoveRow"          // 刪除行之前觸發的事件
                  :after-create-row="hotSettings.afterCreateRow"            // 添加行后觸發的事件                  //一定要記住所有的事件、數值一定要綁定在標簽上才可使用,只在js的data中綁定是不可以的
                  :after-change="hotSettings.afterChange"                   // 新增行,動態改變值觸發的事件
                  :id="`hotTableAll${$route.params.id}`"
                  class="table_hot"
                  license-key="non-commercial-and-evaluation"
                />
              </el-form-item>
              <el-button class="primary-button uploadButton"
                         size="small"
                         type="primary"
                         icon="el-icon-upload"
                         @click="uploadFile">導出</el-button>
</template>
<script>
import addressProvince from '@/components/addressProvince'
import { HotTable } from '@handsontable/vue'
import Handsontable from 'handsontable'
import { Message } from 'element-ui'
import priceList from '@/utils/priceList.js'

// 如果excal中有值為空,可攔截
const validatorList = (rule, value, callback) => {
  for (let i = 0; i < value.length; i++) {
    if (!value[i].region || !value[i].destination) {
      callback(new Error('請輸入價格表中所有信息, 多余的可通過鼠標右擊進行刪除行'))
      return
    }
  }
  callback()
}
const riseWeightVal = function (value, callback) {
  if (/^\d+(?=\.{0,1}\d+$|$)/.test(value) || value === '') {
    callback(true)
  } else {
    Message.error({
      message: '請輸入數字'
    })
    callback(false)
  }
}

export default {
  components: {
    addressProvince,
    HotTable
  },
  data() {
    return {
      addressList: [{
        area: []
      }],
      hotSettings: {
        dataList: [],  //
        colHeaders: ['區域', '目的地', '首重 kg', '首重價格', '續重 kg', '續重價格'],
        startRows: 8,
        startCols: 6,
        rowHeaders: true,
        rowHeights: 40,
        manualRowResize: true,
        manualColumnResize: true,
        manualRowMove: true,
        customBorders: true,
        columns: [
      //data: dataList數組中對應的 鍵,readOnly: 只讀, type: 屬於什么類型 例:text, numeric, validator: 數據驗證 { data: 'region', readOnly: false, type: 'text' }, { data: 'destination', readOnly: false, type: 'text' }, { data: 'firstWeight', readOnly: false, validator: riseWeightVal, allowInvalid: false }, { data: 'firstWeightPrice', readOnly: false, validator: riseWeightVal, allowInvalid: false }, { data: 'riseWeight', readOnly: false, validator: riseWeightVal, allowInvalid: false }, { data: 'riseWeightPrice', readOnly: false, validator: riseWeightVal, allowInvalid: false } ], beforeRemoveRow: this.beforeRemoveRowMe, afterCreateRow: this.afterCreateRowMe, afterChange: this.afterChangeMe, contextMenu: { items: { 'row_above': { name: '在此行上方插入行' }, 'row_below': { name: '在此行下方插入行' }, 'separator': Handsontable.plugins.ContextMenu.SEPARATOR, 'copy': { name: '復制' }, 'undo': { name: '撤消' }, 'separator1': Handsontable.plugins.ContextMenu.SEPARATOR, 'remove_row': { name: '刪除行' }, 'clear_column': { name: '刪除列' }, 'clear_custom': { name: '刪除所有單元格', callback: function () { this.clear() } } } } }, expressCompanyList: [], dateRange: [], typeBol: false, searchParam: { supplierServiceRegionPriceVos: [] }, searchParamRules: { supplierServiceRegionPriceVos: [ { type: 'array', required: true, message: '請填寫價格表', trigger: 'blur' }, { validator: validatorList, required: true, message: '請輸入價格表中所有信息, 多余的可通過鼠標右擊進行刪除行', trigger: 'blur' } ] }, showContent: false, loadShow: false, saveLimit: false } }, mounted() {
   this.hotSettings.dataList = this._.cloneDeep(priceList)
  },
  methods: {
    // 刪除行之前調用
    beforeRemoveRowMe: function (changes, source) { // 數據改變時觸發此方法
      this.hotSettings.dataList.splice(changes, source)
    },
    // 添加行
    afterCreateRowMe: function (changes) {
      this.hotSettings.dataList.splice(changes, 0, {
        region: '',
        destination: '',
        firstWeight: '',
        firstWeightPrice: '',
        riseWeight: '',
        riseWeightPrice: ''
      })
    },
    // 新增行時,動態改變值
    afterChangeMe: function (changes) {
      if (changes) {
        changes.forEach(([row, prop, oldValue, newValue]) => {
          console.log(oldValue)
          this.hotSettings.dataList[row][prop] = newValue
        })
      }
    },
    // 查看-excel不可編輯
    excalEdit() {
      this.hotSettings.columns.forEach(par => {
        par.readOnly = true
      })
    },
    definedShow() {
      this.showContent = true
    },
    saveSubmit() {
      // 防止點擊多次觸發
      if (this.saveLimit) return
    conso.log()
      const that = this
      that.searchParam.supplierServiceRegionPriceVos = that.hotSettings.dataList
      const temp = that._.cloneDeep(this.searchParam)
      that.$refs.searchForm.validate((valid) => {
        if (valid) {
      console.log(this.hotSettings.dataList)
          that.saveLimit = true
        }
      })
    },
    // 導出文件
    uploadFile() {
      // 可查看網址https://handsontable.com/docs/7.1.0/ExportFile.html
      const container = this.$refs.tableServer.hotInstance
      const exportPlugin = container.getPlugin('exportFile')
      exportPlugin.downloadFile('csv', {
        bom: 'UTF-8', // 允許您使用BOM簽名導出數據。
        columnDelimiter: ',', // 允許您定義列分隔符。
        columnHeaders: false, // 允許使用列標題導出數據。
        exportHiddenColumns: true, // 允許您從隱藏列導出數據。
        exportHiddenRows: true, // 允許您從隱藏行導出數據
        fileExtension: 'csv', // 允許您定義文件擴展名。
        filename: '供應商服務價格表[YYYY]-[MM]-[DD]', // 允許您定義文件名。
        mimeType: 'text/csv', // 允許您定義MIME類型。
        rowDelimiter: '\r\n', // 允許您定義行分隔符。
        rowHeaders: true // 允許您使用行標題導出數據。
      })
    }
  }
}
</script>

  

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM