安装xlsx,一定要注意版本:
npm i xlsx@0.17.0 -S
package.json:
- {
- "name": "hello-world",
- "version": "0.1.0",
- "private": true,
- "scripts": {
- "serve": "vue-cli-service serve",
- "build": "vue-cli-service build"
- },
- "dependencies": {
- "element-ui": "^2.15.12",
- "file-saver": "^2.0.5",
- "vue": "^2.6.11",
- "vue-router": "^3.2.0",
- "xlsx": "^0.17.0"
- },
- "devDependencies": {
- "@vue/cli-plugin-babel": "~4.5.0",
- "@vue/cli-plugin-router": "~4.5.0",
- "@vue/cli-plugin-vuex": "~4.5.0",
- "@vue/cli-service": "~4.5.0",
- "babel-plugin-component": "^1.1.1",
- "less": "^3.0.4",
- "less-loader": "^5.0.0",
- "vue-cli-plugin-element": "^1.0.1",
- "vue-template-compiler": "^2.6.11"
- }
- }
App.vue:
- <template>
- <div id="app">
- <el-button type="primary" @click="exportExcel">vue xlsx导出多sheet excel</el-button>
- </div>
- </template>
-
- <script>
- import XLSX from "xlsx";
- export default {
- methods: {
- exportExcel() {
- var data1 = [
- ["id", "name", "hot"],
- [1, "C++", 99],
- [2, "JavaScript", 98]
- ];
- var data2 = [
- ["id", "语言", "热度"],
- [1, "C++", 99],
- [2, "JavaScript", 98]
- ];
- const ws1 = XLSX.utils.aoa_to_sheet(data1);
- const ws2 = XLSX.utils.aoa_to_sheet(data2);
-
- /* generate workbook and add the worksheet */
- const wb = XLSX.utils.book_new();
- // XLSX.utils.book_append_sheet(wb, ws, "test");
- XLSX.utils.book_append_sheet(wb, ws1, "月度统计报表");
- XLSX.utils.book_append_sheet(wb, ws2, "隔离库");
-
- /* save to file */
- XLSX.writeFile(wb, "test.xlsx");
- }
- }
- };
- </script>

设置单元格宽度:
- const ws = XLSX.utils.aoa_to_sheet(data1);
-
- // 每列不同宽度px
- const wscols = [
- { wch: 5 },
- { wch: 60 },
- { wch: 25 }
- ];
-
- ws["!cols"] = wscols;