其实,到现在为止,前面的页面已经实现了对设备数据的展现。这一篇文章中对当前的项目做一个增强:
- 绘制Echarts 图表展示数据变化趋势;
- 导出设备数据到Excel,体验TDengine的查询效率;
这两个功能的实现均需要前后端配合,完成数据交互,我们先实现后端接口,然后在前端调用。
导出Excel图表在实际项目中会遇到各类数据导出的需求,比如将物联网设备数据按照时间范围导出为 Excel 文件以及各种统计结果数据导出为文件的功能。
依赖文件
cn.hutool
hutool-all
5.5.6
org.apache.poi
poi-ooxml
4.1.1
后端接口
通过 poi 与 hutool 工具类,实现从 TDengine 的条件查询功能:指定时间范围内的设备数据导出为 Excel 文件。
- PowerController.java
@GetMapping("exportXls")
public void exportExcel(HttpServletResponse response, @RequestParam Map params) throws IOException, ClassNotFoundException {
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.eq("sn", params.get("sn"));
wrapper.between("ts", params.get("startTime"), params.get("endTime"));
wrapper.orderByDesc("ts");
List powers = powerMapper.selectList(wrapper);
List
前端页面
在 PowerView.vue 中添加以下代码,主要是一个按钮以及导出接口调用,实现将物联网设备数据按照时间范围导出 Excel 文件的功能。
- 结构
导出
- 行为
exportXls: function() {
if (this.deviceDataPage.records.length == 0) {
this.$message({
type: "warning",
message: "暂无数据",
center: false,
showClose: true,
});
return;
}
if (!this.dateRange) {
this.$message({
type: "error",
message: "请选择时间范围!",
showClose: true,
});
return;
}
this.exportLoading = true;
let startTime = this.dateRange[0];
let endTime = this.dateRange[1];
let that = this;
axios
.get(
`/api/power/exportXls?sn=${this.sn}&startTime=${startTime}&endTime=${endTime}`, {
responseType: "blob"
}
)
.then(
function(res) {
if (res.status == 200) {
that.exportLoading = false;
let blob = new Blob([res.data]);
let downloadElement = document.createElement("a");
let href = window.URL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = decodeURI(
res.headers["content-disposition"].substr(
"attachment; filename=".length
)
);
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
} else {
that.exportLoading = false;
console.error(res);
}
},
function(res) {
that.exportLoading = false;
console.error(res);
}
);
},
查询效率
另外,导出 Excel 的功能还重在体验 TDengine 的查询效率。在实际中,曾遇到有的项目中使用前端插件导出 Excel 的方式,这在数据量比较大时,对客户端要求比较高,导出非常慢,影响用户体验。我们这里采用后端直接查询、封装、导出文件的方式实现从亿级记录中导出1万条数据,秒级。
Reference- Vue3.0
- ElementPlus
If you have any questions or any bugs are found, please feel free to contact me.
Your comments and suggestions are welcome!



