1.npm下载并引入:
//安装
npm install --save xlsx file-saver
//需要的页面引入
import XLSX from 'xlsx'
2.data里定义一个参数tableHtml
3.处理方法
methods:{
dealt: function(url) {
let that = this;
var xhr = new XMLHttpRequest()
xhr.open('get', url, true)
xhr.responseType = 'arraybuffer'
xhr.onload = function(e) {
if (xhr.status === 200) {
var data = new Uint8Array(xhr.response)
var workbook = XLSX.read(data, {
type: 'array'
})
that.tableToHtml(workbook)
}
}
xhr.send()
},
tableToHtml: function(workbook) {
var worksheet = workbook.Sheets[workbook.SheetNames[0]];
var innerHTML = XLSX.utils.sheet_to_html(worksheet);
this.tableHtml = innerHTML;
},
}
4.使用
url:get请求的接口
var url = 'xxx';
this.dealt(url)
5.页面
<div class="table-html-wrap" v-html="tableHtml"></div>
因为显示在页面的表格没有边框样式,所以要加如下样式:
6.样式:这里用了scss,自行去安装依赖。
<style scoped lang="scss">
.table-html-wrap /deep/ table {
border-right: 1px solid #e8eaec;
border-bottom:1px solid #e8eaec;
border-collapse: collapse;
margin: auto;
}
.table-html-wrap /deep/ table td {
border-left: 1px solid #e8eaec;
border-top: 1px solid #e8eaec;
white-space: nowrap;
text-align: center;
padding: .5rem;
}
.table-html-wrap /deep/ tbody tr:nth-of-type(1) {
font-weight: bold;
font-size: 20px;
}
</style>
注意:
在安装vue安装scss时,可能报错:The “path” argument must be of type string. Received undefined
解决:这个错误是sass-loader 高版本造成的,修改版本为 “sass-loader”: “^7.3.1”,
重新使用命令安装“npm install sass-loader@7 –D”即可
如果有疑问,可以指出,谢谢~