设置element组件表格:表头样式、单元格样式、表尾合计、边框、行高

发布时间 2023-12-23 17:37:10作者: 借你耳朵说爱你

设置表格头样式

methods: {
    headerCellClassName({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0) {
            return { textAlign: 'center', background: '#FFD966', fontWeight: 'bold', color:'#000000', fontSize:'16px' };
        }
        if (rowIndex === 1 && (columnIndex === 0 || columnIndex === 8 || columnIndex === 9)) {
            return { textAlign: 'center', background: '#FFD966', fontWeight: 'bold', color:'#000000' };
        }
        if (rowIndex === 1 && (columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4 || columnIndex === 5 || columnIndex === 6)) {
            return { textAlign: 'center', background: '#FFD966', fontWeight: 'bold', color:'#FF0000' };
        }
        if (rowIndex === 1 && columnIndex === 7) {
            return { textAlign: 'center', background: '#FFE699', fontWeight: 'bold', color:'#000000' };
        }
    },
}

设置数据单元格样式

methods: {
    cellStyle({ row, column, rowIndex, columnIndex }) {
        if (column.property === "lastAmount") {
            return 'style-row';
        }
    },
},

<style>
  .el-table .style-row {
       background: #BDD7EE;
  }
</style>

表格添加统计行

methods: {
    getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
            if (index === 0) {
                sums[index] = '小计';
                return;
            }
            const values = data.map(item => Number(item[column.property]));
            if (index < 8 && !values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return prev + curr;
                    } else {
                        return prev;
                    }
                }, 0);
                sums[index] = this.toFixed(sums[index]);
            }
        });
        sums.push(((String(sums[2]).replaceAll(",","") / String(sums[1]).replaceAll(",","")) * 100).toFixed(1) + "%");
        sums.push(((String(sums[1]).replaceAll(",","") - String(sums[6]).replaceAll(",","")) / String(sums[6]).replaceAll(",","") * 100).toFixed(1) + "%");
        return sums;
    },
}

设置表格边框

<style>
  .elTable {
    border: 1.5px solid black;
  }
  .elTable th {
    border: 1px solid black;
  }
  .elTable td {
    border: 1px solid black;
  }
</style>

设置表格行高

<style>
  .elTable th {
    padding: 0 !important;
    height: 30px;
    line-height: 30px;
  }
  .elTable td {
    padding: 0 !important;
    height: 40px;
    line-height: 40px;
  }
</style>

表格引用style

<el-table
    :data="collectionTableData"
    :header-cell-style="collectionHeaderCellClassName"
    :cell-class-name="collectionCellStyle"
    class="elTable"
:summary-method="getSummaries" show-summary> </el-table>