在項目開發時免不了有時會用到表格數據導出excel的功能,以前會用file-saver xlsx script-loader來導出,而且配置非常麻煩,現在用vue-json-excel配置及使用都非常簡單
一、安裝vue-json-excel
npm install vue-json-excel -S
- 1
二、main.js里面引入並注冊使用
import JsonExcel from 'vue-json-excel'
Vue.component('downloadExcel', JsonExcel)
三、頁面中使用
<download-excel
class = "export-excel-wrapper"
:data = "json_data"
:fields = "json_fields"
name = "filename.xls">
<!-- 上面可以自定義自己的樣式,還可以引用其他組件button -->
<!-- <el-button type="primary" size="small">導出EXCEL</el-button> -->
</download-excel>
在這里說明一下組件的各個屬性
- json_data:需要導出的數據
- json_fields:自主選擇要導出的字段,若不指定,默認導出全部數據中心全部字段
| 屬性名 | 類型 | 描述 |
|---|---|---|
| data | Array | 需要導出的數據,支持中文 |
| fields | Object | 定義需要導出數據的字段 |
| name | String | 導出excel的文件名 |
| type | String | 導出excel的文件類型(xls,csv),默認是xls |
下面給個實例
注意以下幾點
- json_fields里面的屬性是excel表每一列的title,注意多個詞組組成的屬性名要加雙引號
- 如果需要自定義導出的數據,可以定義回調函數。
data() {
return {
json_fields: {
"Complete name": "name", //常規字段
Telephone: "phone.mobile", //支持嵌套屬性
"Telephone 2": {
field: "phone.landline",
//自定義回調函數
callback: value => {
return `Landline Phone - ${value}`;
}
}
},
json_data: [
{
name: "Tony Peña",
city: "New York",
country: "United States",
birthdate: "1978-03-15",
phone: {
mobile: "1-541-754-3010",
landline: "(541) 754-3010"
}
},
{
name: "Thessaloniki",
city: "Athens",
country: "Greece",
birthdate: "1987-11-23",
phone: {
mobile: "+1 855 275 5071",
landline: "(2741) 2621-244"
}
}
],
json_meta: [
[
{
" key ": " charset ",
" value ": " utf- 8 "
}
]
]
};
}
