uni-table表格官方插件不支持表头固定,在原插件的基础上修改样式以达到固定表头目的,要点是在表头、表体外层分别加上 <view class="table_header"> ,<view class="table_body">
针对这两部分写样式。
css
.table_header {
position: relative;
top: 0;
left: 0;
background-color: #d4d4d4;
}
.table_body{
overflow: scroll;
height: 1000rpx;
}
以下是完整代码:
javascript
<template>
<view class="content">
<!-- 表格插件 https://uniapp.dcloud.net.cn/component/uniui/uni-table.html -->
<uni-table border stripe emptyText="暂无更多数据" >
<!-- 表头行 -->
<view class="table_header">
<uni-tr>
<uni-th align="center" width="190rpx">用户</uni-th>
<uni-th align="center" width="300rpx">题目</uni-th>
<uni-th align="left" width="300rpx">选项</uni-th>
</uni-tr>
</view>
<!-- 表格数据行 -->
<view class="table_body">
<uni-tr v-for="(item,index) in dataList" :key="index">
<uni-td> <view style="width:150rpx;text-align:center;">{{item.userName}}</view> </uni-td>
<uni-td> <view style="width:256rpx;text-align:center;">{{item.subjectContent}}</view> </uni-td>
<uni-td> <view style="width:256rpx;text-align:left;">{{item.optionContent}}</view> </uni-td>
</uni-tr>
</view>
</uni-table>
<!-- 导出按键 -->
<view style="width: 100%; height: 150rpx;">
<button style="width: 50%; margin-top: 20rpx;" type="primary" @click="exportXlsx">数据导出为.xlsx</button>
</view>
</view>
</template>
<script>
import XLSX from "@/static/xlsx.full.min.js"; //引入XLSX;下载链接https://cdn.sheetjs.com/
export default {
data() {
return {
baseUrl: '',
dataList: []
}
},
onLoad() {
// 获取全局变量 baseUrl
this.baseUrl = getApp().globalData.baseUrl;
// 调用方法
this.getData()
},
methods: {
//从后端获取数据
getData() {
uni.request({
url: this.baseUrl + 'queryAnswer',
method: "GET",
data: {},
success: (res) => {
let arr = res.data.dataArr
// console.log(arr)
this.dataList = arr
},
fail: () => {
uni.showToast({
title: "网络请求失败!",
icon: 'none',
duration: 2000
})
}
})
},
// 数据导出为xlsx
exportXlsx() {
// 数据
let dataList = this.dataList
let sheet = []
// 表头
let title = ['用户', '题目','选项']
sheet.push(title)
// 从源数组循环提取需要的字段追加到新数组
dataList.forEach(item => {
let rowcontent = []
rowcontent.push(item.userName)
rowcontent.push(item.subjectContent)
rowcontent.push(item.optionContent)
sheet.push(rowcontent)
})
// XLSX插件使用
var worksheet = XLSX.utils.aoa_to_sheet(sheet);
var workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, "导出信息");
// H5导出
XLSX.writeFile(workbook, '导出.xlsx');
}
}
}
</script>
<style>
.content{
width: 100%;
}
.table_header {
position: relative;
top: 0;
left: 0;
background-color: #d4d4d4;
}
.table_body{
overflow: scroll;
height: 1000rpx;
}
</style>