安装xlsx
npm install xlsx
import * as XLSX from 'xlsx';
在页面中定义一个div来展示html数据
<div class="file-input" id="file-input" v-html="excelData"></div>
定义二进制流请求接口
export function getExcel(data: any) {
return axios({
url: 'xxx',
method: 'post',
responseType: 'blob',
data,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
});
}
拿到数据并展示
const excelData = ref(null)
const dealFile = () => {
let params = {}
getExcel(params).then(async (res: any) => {
loading.value = false
const blob = new Blob([res.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
})
const arrayBuffer = await blob.arrayBuffer()
const workbook = await XLSX.read(arrayBuffer, {type: 'array'})
const sheetName = workbook.SheetNames[0]
const worksheet = workbook.Sheets[sheetName]
console.log('worksheet ', worksheet)
try {
if (worksheet) {
const html = XLSX.utils.sheet_to_html(worksheet, {
header: `
<style>
.xlsx-table {
border-collapse: collapse;
width: 100%;
margin: 1rem 0;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
.xlsx-table th, .xlsx-table td {
border: 1px solid #e0e0e0;
padding: 10px 12px;
text-align: left;
min-width: 150px;
}
.xlsx-table th {
background-color: #f5f7fa;
font-weight: 600;
color: #333;
min-width: 150px;
}
.xlsx-table tr:nth-child(even) {
background-color: #f9f9f9;
}
.xlsx-table tr:hover {
background-color: #f1f5f9;
}
</style>
`
})
excelData.value = html.replace('<table', '<table class="xlsx-table"');
} else {
excelData.value = '<div style="text-align: center;height:200px;line-height: 200px">暂无数据</div>'
}
} catch (error) {
excelData.value = '<div style="text-align: center;height:200px;line-height: 200px">暂无数据</div>'
}
})
}