excel 导入导出
相关文档
midwayjs 文件上传open in new window
node-xlsx 模块open in new window
DEMO 示例
import { Get, Inject, Post, Provide } from "@midwayjs/decorator";
import { CoolController, BaseController } from "@cool-midway/core";
import xlsx from "node-xlsx";
import * as XLSX from "xlsx";
import { Context } from "egg";
import * as fs from "fs";
/**
* 导入导出
*/
@Provide()
@CoolController()
export class DemoExcelController extends BaseController {
@Inject()
ctx: Context;
/**
* 导入
*/
@Post("/import")
async import() {
// 读取上传上来的文件
const file = this.ctx.request.files[0];
try {
// 解析文件
const data = xlsx.parse(file.filepath);
console.log(data);
// xlsx包使用方式
// const data = XLSX.readFile(file.filepath, {});
// const json = XLSX.utils.sheet_to_json(data.Sheets['Sheet1']);
} finally {
fs.unlinkSync(file.filepath);
}
return this.ok();
}
/**
* 导出
*/
@Get("/export")
async export() {
const data = [
["姓名", "年龄"],
["啊平", 18],
["江帅", 19],
];
const buffer = xlsx.build([{ name: "成员", data: data }]);
const fileName = "导出.xlsx";
this.ctx.attachment(fileName);
this.ctx.status = 200;
this.ctx.body = buffer;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54