提交 0ce8481a 编写于 作者: sq3536's avatar sq3536

调整报表

上级 ef9f2ef9
...@@ -24,7 +24,7 @@ ...@@ -24,7 +24,7 @@
padding: 10px 0; padding: 10px 0;
> .vue-treeselect { > .vue-treeselect {
width: 14%; width: 300px;
> .vue-treeselect__control { > .vue-treeselect__control {
height: 40px; height: 40px;
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
} }
> .el-select { > .el-select {
width: 9%; width: 150px;
} }
} }
......
...@@ -7,34 +7,37 @@ ...@@ -7,34 +7,37 @@
</h6> </h6>
<div class="content-container"> <div class="content-container">
<div class="selectAndData"> <div class="selectAndData">
<Treeselect ref="orgid" v-model="treeValue" :options="treeOptions" placeholder="请选择单位或区域" ></Treeselect> <Treeselect ref="dim" v-model="treeValue" :options="treeOptions" :normalizer="normalizer" :placeholder='dimPlaceholder' ></Treeselect>
<el-select ref="cxfs" v-model="computedSelectVal" placeholder="请选择查询方式" > <el-select ref="cxfs" v-model="type" @change="typechange" placeholder="请选择查询方式" >
<template v-if='options && options.length>0'> <template v-if='options && options.length>0'>
<template v-for='(item) in options'> <template v-for='(item) in options'>
<el-option :key="item.value" :value="item.value" :label="item.label" ></el-option> <el-option :key="item.value" :value="item.value" :label="item.label" ></el-option>
</template> </template>
</template> </template>
</el-select> </el-select>
<el-date-picker ref="time" v-model="dataValue" :type='type' range-separator='至' :start-placeholder='startPlaceholder' :end-placeholder='endPlaceholder'></el-date-picker> <el-date-picker ref="time" v-model="dataValue" value-format="yyyy-MM-dd" :type='type' range-separator='至' start-placeholder='起始' end-placeholder='结束'></el-date-picker>
<div class="toolbar" style="margin-left: auto">
<div class="toolbar" style="margin-left: auto" >
<el-button @click="exportReport">导出</el-button>
<el-button @click="getReportData">搜索</el-button> <el-button @click="getReportData">搜索</el-button>
</div> </div>
</div> </div>
<div class="grid"> <div class="grid">
<ag-grid-vue <ag-grid-vue
style="width: 100%; height: 95%" style="width: 100%; height: 95%"
class="ag-theme-balham" class="ag-theme-balham"
:columnDefs="columnDefs" :columnDefs="columnDefs"
:enableSorting="true"
:enableFilter="false" :enableFilter="false"
:enableColResize="true" :enableColResize="true"
:singleClickEdit="true" :singleClickEdit="true"
:pagination="false" :pagination="false"
rowSelection="multiple"
:localeText="localeText" :localeText="localeText"
headerHeight=30
@onGridReady="onGridReady" @onGridReady="onGridReady"
@onselectionChanged="selectionChanged" @onselectionChanged="selectionChanged"
@onrowDoubleClicked="rowDoubleClicked" @onrowDoubleClicked="rowDoubleClicked"
@onCellDoubleClicked="onCellClick"
:rowData="items" :rowData="items"
></ag-grid-vue> ></ag-grid-vue>
</div> </div>
...@@ -78,8 +81,14 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase { ...@@ -78,8 +81,14 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase {
if (_this.loadModel && _this.loadModel instanceof Function) { if (_this.loadModel && _this.loadModel instanceof Function) {
_this.loadModel(); _this.loadModel();
} }
_this.getXQCodelist(); _this.getReport(false);
_this.getReportData(); }
public normalizer(node){
//去掉children=null的属性
if(node.children==null||node.children=='null'){
delete node.children;
}
} }
/** /**
...@@ -87,24 +96,10 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase { ...@@ -87,24 +96,10 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase {
*/ */
public columnDefs: any[] = []; public columnDefs: any[] = [];
public headname: any = ''; public headname: any = '';
public dimPlaceholder: any='请选择';
/**
* select绑定值
*/
@Prop() public selectValue: any;
/**
* 计算绑定值
*/
set computedSelectVal(val: any) {
this.selectValue = val;
Object.assign(this.context,{dictcatalog:'CL_DST_REGION'});
this.viewparams
}
get computedSelectVal() {
return this.selectValue;
}
/** /**
* 选项值 * 选项值
...@@ -115,11 +110,11 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase { ...@@ -115,11 +110,11 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase {
label: '按年查询', label: '按年查询',
}, },
{ {
value: 'month', value: 'monthrange',
label: '按月查询', label: '按月查询',
}, },
{ {
value: 'day', value: 'daterange',
label: '按日查询', label: '按日查询',
} }
]; ];
...@@ -127,47 +122,15 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase { ...@@ -127,47 +122,15 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase {
/** /**
* data绑定值 * data绑定值
*/ */
@Model('dataChange') dataValue: any; public dataValue: any =[];
/**
* 计算绑定值
*/
set computedDataVal(val: any) {
this.$emit('dataChange', val);
}
get computedDataVal() {
return this.dataValue;
}
/** /**
* 选择类型 * 选择类型
*/ */
public type: any; public type: any='daterange';
public startPlaceholder: any;
public endPlaceholder: any;
/**
* 监听selectValue
* @param newVal
* @param oldVal
*/
@Watch('selectValue')
onselectionchange(newVal: any, oldVal: any) {
if (newVal === 'year') {
this.type = 'year';
}
if (newVal === 'month') {
this.type = 'monthrange';
this.startPlaceholder = '开始月份';
this.endPlaceholder = '结束月份';
}
if (newVal === 'day') {
this.type = 'daterange';
this.startPlaceholder = '开始日期';
this.endPlaceholder = '结束日期';
}
}
/** /**
* 树项 * 树项
...@@ -178,85 +141,84 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase { ...@@ -178,85 +141,84 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase {
* 树值 * 树值
* @param $event * @param $event
*/ */
@Model('treeChange') treeValue: any; public treeValue: any = "";
public typechange(node:any)
{
if(node=='year')
this.dataValue="";
/**
* 计算绑定值
*/
set computedtreeVal(val: any) {
this.$emit('treeChange', val);
}
get computedtreeVal() {
return this.treeValue;
} }
/**
* 获取辖区代码表 public startTime : any;
*/ public endTime : any;
public getXQCodelist(){
// 请求地址 public getTimeRange()
const post: Promise<any> = this.$http.post("/ibizutil/getCodelist", { cid: "CL_DST_REGION"}, true); {
post.then((response: any) => { const time: any = this.$refs.time;
if (response && response.status == 200) { let timeAll = time.displayValue;
this.treeOptions = response.data; if (this.type === "year") {
} this.startTime = timeAll + '-01-01';
}).catch((response: any) => { this.endTime = timeAll + '-12-31';
if (!response || !response.status || !response.data) { }
this.$Notice.error({ title: '错误', desc: '系统异常' }); if (this.type === "monthrange") {
return; this.startTime = timeAll[0] + '-01';
} this.endTime = timeAll[1] + '-31';
const { data: _data } = response; }
this.$Notice.error({ title: _data.title, desc: _data.message }); if (this.type === "daterange") {
}); this.startTime = timeAll[0];
this.endTime = timeAll[1];
}
} }
/** /**
* 请求数据 * 请求数据
*/ */
public getReportData() { public getReportData()
{
this.getReport(true);
}
public getReport(loadData?: boolean) {
const _this:any = this; const _this:any = this;
// 置空表格数据
this.columnDefs = []; this.getTimeRange();
// 机构
const orgid: any = this.$refs.orgid;
let domin = orgid.value;
// 类型
const cxfs: any = this.$refs.cxfs;
let fs = cxfs.value;
// 时间
const time: any = this.$refs.time;
let timeAll = time.displayValue;
let startTime: any;
let endTime: any;
if (fs === "year") {
startTime = timeAll + '-01-01';
endTime = timeAll + '-12-31';
}
if (fs === "month") {
startTime = timeAll[0] + '-01';
endTime = timeAll[1] + '-31';
}
if (fs === "day") {
startTime = timeAll[0];
endTime = timeAll[1];
}
// 请求地址 // 请求地址
debugger //debugger
const post: Promise<any> = this.$http.post('/ibizutil/reportdatas', { id: JSON.parse(this.viewdata).srfparentkey, domin: domin, startTime: startTime, endTime: endTime }, true); let url='/lite/report/'+JSON.parse(this.viewdata).srfparentkey;
if(!loadData)
url=url+"/config";
else if(this.treeValue&&this.treeValue!='%')
url=url+"/"+this.treeValue;
if(this.startTime&&this.endTime)
url=url+"?startTime="+this.startTime+"&endTime="+this.endTime;
const params: any = {};
const post: Promise<any> = this.$http.get(url,params,true);
post.then((response: any) => { post.then((response: any) => {
if (response && response.status == 200) { if (response && response.status == 200) {
this.headname = response.data.reportname;
let reportname = { this.headname = response.data.title;
headerName: response.data.reportname, if((!loadData)||this.columnDefs.length==0)
field: '',//显示数据的字段名 this.columnDefs=response.data.headers;
filter: '',//过滤的类型 if(loadData)
width: '', this.items = response.data.rows;
cellStyle: { color: 'red' },//单元格样式
children: response.data.resportdata.headData,//子项 if((!loadData)||this.treeOptions.length==0)
}; this.treeOptions=response.data.dict.items;
this.items = response.data.resportdata.erportdata[0]; this.treeValue=response.data.selectValue;
this.columnDefs.push(reportname); this.dimPlaceholder="请选择"+response.data.group;
if(!this.startTime)
{
this.type="daterange"
this.dataValue=[response.data.startTime,response.data.endTime]
}
} }
}).catch((response: any) => { }).catch((response: any) => {
if (!response || !response.status || !response.data) { if (!response || !response.status || !response.data) {
...@@ -269,6 +231,26 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase { ...@@ -269,6 +231,26 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase {
} }
/**
* 请求数据
*/
public exportReport() {
const _this:any = this;
// 时间
this.getTimeRange()
// 请求地址
//debugger
let url='/lite/report/'+JSON.parse(this.viewdata).srfparentkey;
if(this.treeValue&&this.treeValue!='%')
url=url+"/"+this.treeValue;
if(this.startTime&&this.endTime)
url=url+".xls?startTime="+this.startTime+"&endTime="+this.endTime;
window.open(url);
}
/** /**
* 表格对象 * 表格对象
* *
...@@ -290,7 +272,7 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase { ...@@ -290,7 +272,7 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase {
* @type {any[]} * @type {any[]}
* @memberof Main * @memberof Main
*/ */
public items: any = new Array(); public items: any = [];
/** /**
* 表格数据 * 表格数据
...@@ -334,7 +316,7 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase { ...@@ -334,7 +316,7 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase {
valueColumnsEmptyMessage: "la drag cols to aggregate", valueColumnsEmptyMessage: "la drag cols to aggregate",
pivotColumnsEmptyMessage: "la drag here to pivot", pivotColumnsEmptyMessage: "la drag here to pivot",
toolPanelButton: "la tool panel", toolPanelButton: "la tool panel",
noRowsToShow: "数据为空", noRowsToShow: "选定统计条件,点击【搜索】按钮加载数据",
pinColumn: "laPin Column", pinColumn: "laPin Column",
valueAggregation: "laValue Agg", valueAggregation: "laValue Agg",
autosizeThiscolumn: "laAutosize Diz", autosizeThiscolumn: "laAutosize Diz",
...@@ -407,5 +389,10 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase { ...@@ -407,5 +389,10 @@ export default class DAReportBBZSCustomView extends DAReportBBZSCustomViewBase {
console.log($event.data); console.log($event.data);
} }
public onCellClick($event:any): void{
console.log($event.data);
const _this = this;
}
} }
</script> </script>
\ No newline at end of file
package cn.ibizlab.core.extensions.domain; package cn.ibizlab.core.extensions.domain;
import cn.ibizlab.core.lite.extensions.domain.ModelObj; import cn.ibizlab.core.lite.extensions.domain.ModelObj;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data; import lombok.Data;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
...@@ -9,6 +12,7 @@ import java.math.BigDecimal; ...@@ -9,6 +12,7 @@ import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; import java.util.List;
@Data @Data
...@@ -30,6 +34,8 @@ public class BaseRequest ...@@ -30,6 +34,8 @@ public class BaseRequest
'}'; '}';
} }
@JsonIgnore
@JSONField(serialize = false)
public String toString2() { public String toString2() {
return "BaseRequest{" + return "BaseRequest{" +
"id='" + id + '\'' + "id='" + id + '\'' +
...@@ -42,6 +48,7 @@ public class BaseRequest ...@@ -42,6 +48,7 @@ public class BaseRequest
} }
private List<ModelObj> datas; private List<ModelObj> datas;
private String modelId;
private String model; private String model;
private String engineId; private String engineId;
private String resultDataSource; private String resultDataSource;
...@@ -50,17 +57,26 @@ public class BaseRequest ...@@ -50,17 +57,26 @@ public class BaseRequest
private List<String> rules; private List<String> rules;
private List<String> ruleIds; private List<String> ruleIds;
private SimpleDateFormat format =new SimpleDateFormat("yyyyMMddHHmmss"); private HashSet<String> fillpropertys;
public String getBatch() public String getBatch()
{ {
if(batch==null || batch.equals("")) if(batch==null || batch.equals(""))
{ {
batch= format.format(new java.util.Date())+"["+model+"]"; batch= new SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date())+"["+model+"]";
} }
return this.batch; return this.batch;
} }
public BaseRequest copy(boolean reset)
{
BaseRequest baseRequest = JSON.parseObject(JSON.toJSONString(this),BaseRequest.class);
return baseRequest;
}
} }
...@@ -30,35 +30,43 @@ import java.util.*; ...@@ -30,35 +30,43 @@ import java.util.*;
@Accessors(chain = true) @Accessors(chain = true)
public class FetchParam { public class FetchParam {
@JsonIgnore
@JSONField(serialize = false)
private String id;
@JsonIgnore @JsonIgnore
@JSONField(serialize = false) @JSONField(serialize = false)
public String getId() { public String getId() {
String str = "FetchParam{" + if(StringUtils.isEmpty(id))
"reportId='" + reportId + '\'' + {
", chartId='" + chartId + '\'' + String str = "FetchParam{" +
", buildId='" + buildId + '\'' + "reportId='" + reportId + '\'' +
", displayType='" + displayType + '\'' + ", chartId='" + chartId + '\'' +
", dimDict='" + dimDict + '\'' + ", buildId='" + buildId + '\'' +
", dimValues=" + dimValues + ", displayType='" + displayType + '\'' +
", dimValue='" + dimValue + '\'' + ", dimDict='" + dimDict + '\'' +
", includeChild=" + includeChild + ", dimValues=" + dimValues +
", metricIds=" + metricIds + ", dimValue='" + dimValue + '\'' +
", metricId='" + metricId + '\'' + ", includeChild=" + includeChild +
", startTime=" + startTime + ", metricIds=" + metricIds +
", endTime=" + endTime + ", metricId='" + metricId + '\'' +
", page=" + page + ", startTime=" + startTime +
", size=" + size + ", endTime=" + endTime +
", total=" + total + ", page=" + page +
", group='" + group + '\'' + ", size=" + size +
'}'; ", total=" + total +
return DigestUtils.md5DigestAsHex(str.getBytes()); ", group='" + group + '\'' +
'}';
id = DigestUtils.md5DigestAsHex(str.getBytes());
}
return id;
} }
private String reportId; private String reportId;
private String chartId; private String chartId;
private String buildId; private String buildId;
private String title;
// 表格展示类型:1. default(维度数据以行的形式展示),2. LIST_BOX(维度数据以列的形式展示) // 表格展示类型:1. default(维度数据以行的形式展示),2. LIST_BOX(维度数据以列的形式展示)
private String displayType = "default"; private String displayType = "default";
......
...@@ -3,6 +3,7 @@ package cn.ibizlab.core.extensions.dto; ...@@ -3,6 +3,7 @@ package cn.ibizlab.core.extensions.dto;
import cn.ibizlab.core.analysis.domain.DAMetric; import cn.ibizlab.core.analysis.domain.DAMetric;
import cn.ibizlab.util.dict.Catalog; import cn.ibizlab.util.dict.Catalog;
import cn.ibizlab.util.dict.CodeItem; import cn.ibizlab.util.dict.CodeItem;
import cn.ibizlab.util.dict.Option;
import cn.ibizlab.util.helper.DataObject; import cn.ibizlab.util.helper.DataObject;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
...@@ -30,6 +31,8 @@ public class FetchResult { ...@@ -30,6 +31,8 @@ public class FetchResult {
// 表格展示类型:1. default(维度数据以行的形式展示),2. LIST_BOX(维度数据以列的形式展示) // 表格展示类型:1. default(维度数据以行的形式展示),2. LIST_BOX(维度数据以列的形式展示)
private String displayType = "default"; private String displayType = "default";
private String title;
private List<FetchItem> rows; private List<FetchItem> rows;
private List<VMConfig> headers; private List<VMConfig> headers;
...@@ -38,8 +41,8 @@ public class FetchResult { ...@@ -38,8 +41,8 @@ public class FetchResult {
if(headers==null) if(headers==null)
{ {
headers = new ArrayList<>(); headers = new ArrayList<>();
headers.add(new VMConfig().setHeaderName("序号").setEntity("item").setField("no").setPinned("left")); headers.add(new VMConfig().setHeaderName("序号").setEntity("item").setWidth(50).setField("no").setPinned("left"));
headers.add(new VMConfig().setHeaderName(getGroup()).setEntity("item").setField("itemName").setPinned("left")); headers.add(new VMConfig().setHeaderName(getGroup()).setEntity("item").setWidth(250).setField("itemName").setPinned("left"));
if(vmConfigs!=null) if(vmConfigs!=null)
headers.addAll(vmConfigs); headers.addAll(vmConfigs);
} }
...@@ -104,14 +107,17 @@ public class FetchResult { ...@@ -104,14 +107,17 @@ public class FetchResult {
@JSONField(serialize = false) @JSONField(serialize = false)
private List<VMConfig> vmConfigs; private List<VMConfig> vmConfigs;
@JsonIgnore
@JSONField(serialize = false)
private String group; private String group;
private Catalog dict; private Catalog dict;
private String selectValue; private String selectValue;
@JsonIgnore
@JSONField(serialize = false)
private Option selectDimItem;
@JsonFormat(pattern = "yyyy-MM-dd", locale = "zh", timezone = "GMT+8") @JsonFormat(pattern = "yyyy-MM-dd", locale = "zh", timezone = "GMT+8")
@JSONField(name = "startTime", format = "yyyy-MM-dd") @JSONField(name = "startTime", format = "yyyy-MM-dd")
private Timestamp startTime; private Timestamp startTime;
...@@ -119,6 +125,12 @@ public class FetchResult { ...@@ -119,6 +125,12 @@ public class FetchResult {
@JSONField(name = "endTime", format = "yyyy-MM-dd") @JSONField(name = "endTime", format = "yyyy-MM-dd")
private Timestamp endTime; private Timestamp endTime;
private String snapId;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8")
@JSONField(name = "snapTime", format = "yyyy-MM-dd HH:mm:ss")
private Timestamp snapTime;
public static FetchResult from(FetchParam fetchParam) public static FetchResult from(FetchParam fetchParam)
{ {
FetchResult fetchResult=new FetchResult(); FetchResult fetchResult=new FetchResult();
...@@ -129,7 +141,8 @@ public class FetchResult { ...@@ -129,7 +141,8 @@ public class FetchResult {
fetchResult.setVmConfigs(fetchParam.getVmConfigs()); fetchResult.setVmConfigs(fetchParam.getVmConfigs());
} }
fetchResult.setGroup(StringUtils.isEmpty(fetchParam.getGroup())?"分项":fetchParam.getGroup()); fetchResult.setGroup(StringUtils.isEmpty(fetchParam.getGroup())?"分项":fetchParam.getGroup());
fetchResult.setDict(fetchParam.getDict()).setSelectValue(fetchParam.getDimValue()).setStartTime(fetchParam.getStartTime()).setEndTime(fetchParam.getEndTime()); fetchResult.setTitle(fetchParam.getTitle()).setDict(fetchParam.getDict()).setSelectValue(fetchParam.getDimValue()).setStartTime(fetchParam.getStartTime()).setEndTime(fetchParam.getEndTime()).setSelectDimItem(fetchParam.getDimItem());
return fetchResult; return fetchResult;
} }
......
...@@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONArray; ...@@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
...@@ -18,10 +19,18 @@ import java.util.*; ...@@ -18,10 +19,18 @@ import java.util.*;
@Getter @Getter
@Setter @Setter
@NoArgsConstructor @NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@Accessors(chain = true) @Accessors(chain = true)
public class VMConfig { public class VMConfig {
private String headerName; private String headerName;
private Integer width; private Integer width;
public Integer getWidth() {
if(width==null&&(!StringUtils.isEmpty(field)))
return 100;
return width;
}
@JSONField(name = "entity") @JSONField(name = "entity")
@JsonProperty("entity") @JsonProperty("entity")
private String entity; private String entity;
...@@ -29,8 +38,16 @@ public class VMConfig { ...@@ -29,8 +38,16 @@ public class VMConfig {
@JsonProperty("field") @JsonProperty("field")
private String field; private String field;
private String pinned; private String pinned;
private Boolean hide;
private List<VMConfig> children; private List<VMConfig> children;
@JsonIgnore
@JSONField(serialize = false)
public boolean isHide()
{
return hide!=null&&hide;
}
public void setChildren(List<VMConfig> children) { public void setChildren(List<VMConfig> children) {
if(children!=null) if(children!=null)
children.forEach(item->{ children.forEach(item->{
......
...@@ -10,15 +10,19 @@ import cn.ibizlab.core.analysis.service.impl.DAReportServiceImpl; ...@@ -10,15 +10,19 @@ import cn.ibizlab.core.analysis.service.impl.DAReportServiceImpl;
import cn.ibizlab.core.dict.extensions.service.DictDstService; import cn.ibizlab.core.dict.extensions.service.DictDstService;
import cn.ibizlab.core.extensions.cql.ExecResultRepository; import cn.ibizlab.core.extensions.cql.ExecResultRepository;
import cn.ibizlab.core.extensions.dto.*; import cn.ibizlab.core.extensions.dto.*;
import cn.ibizlab.core.extensions.util.ExcelTool;
import cn.ibizlab.core.rule.domain.ExecResult; import cn.ibizlab.core.rule.domain.ExecResult;
import cn.ibizlab.core.rule.service.IExecResultService; import cn.ibizlab.core.rule.service.IExecResultService;
import cn.ibizlab.util.dict.Catalog; import cn.ibizlab.util.dict.Catalog;
import cn.ibizlab.util.dict.CodeItem; import cn.ibizlab.util.dict.CodeItem;
import cn.ibizlab.util.dict.CodeList; import cn.ibizlab.util.dict.CodeList;
import cn.ibizlab.util.dict.Option; import cn.ibizlab.util.dict.Option;
import cn.ibizlab.util.helper.DataObject;
import cn.ibizlab.util.helper.Setting; import cn.ibizlab.util.helper.Setting;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder; import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.datastax.driver.core.PagingState; import com.datastax.driver.core.PagingState;
import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSet;
...@@ -36,8 +40,12 @@ import org.springframework.util.Assert; ...@@ -36,8 +40,12 @@ import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.io.File;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import static com.datastax.driver.core.querybuilder.QueryBuilder.lte; import static com.datastax.driver.core.querybuilder.QueryBuilder.lte;
...@@ -82,6 +90,10 @@ public class BuildResultService { ...@@ -82,6 +90,10 @@ public class BuildResultService {
@Lazy @Lazy
private ExecResultExService execResultExService; private ExecResultExService execResultExService;
@Autowired
@Lazy
BuildResultService proxy;
@Value("${defaultResultDataSource:default}") @Value("${defaultResultDataSource:default}")
private String Default_ResultDataSource; private String Default_ResultDataSource;
...@@ -89,7 +101,7 @@ public class BuildResultService { ...@@ -89,7 +101,7 @@ public class BuildResultService {
private String Default_ResultTableName; private String Default_ResultTableName;
private void prepareFetchParam(FetchParam fetchParam) public void prepareFetchParam(FetchParam fetchParam)
{ {
if(fetchParam.isFilled()) if(fetchParam.isFilled())
return; return;
...@@ -109,6 +121,7 @@ public class BuildResultService { ...@@ -109,6 +121,7 @@ public class BuildResultService {
if(!StringUtils.isEmpty(daReport.getGroup())) if(!StringUtils.isEmpty(daReport.getGroup()))
fetchParam.setGroup(daReport.getGroup()); fetchParam.setGroup(daReport.getGroup());
fetchParam.setTitle(daReport.getReportName());
} }
} }
else if(!StringUtils.isEmpty(fetchParam.getChartId())) else if(!StringUtils.isEmpty(fetchParam.getChartId()))
...@@ -123,6 +136,8 @@ public class BuildResultService { ...@@ -123,6 +136,8 @@ public class BuildResultService {
if(!StringUtils.isEmpty(daChart.getGroup())) if(!StringUtils.isEmpty(daChart.getGroup()))
fetchParam.setGroup(daChart.getGroup()); fetchParam.setGroup(daChart.getGroup());
fetchParam.setTitle(daChart.getChartName());
} }
} }
...@@ -201,7 +216,8 @@ public class BuildResultService { ...@@ -201,7 +216,8 @@ public class BuildResultService {
dimValues.add(codeItem.getValue().toString()); dimValues.add(codeItem.getValue().toString());
}); });
} }
dimValues.add(fetchParam.getDimValue()); if(dimValues.size()==0)
dimValues.add(fetchParam.getDimValue());
fetchParam.setDimValues(dimValues); fetchParam.setDimValues(dimValues);
} }
...@@ -473,7 +489,7 @@ public class BuildResultService { ...@@ -473,7 +489,7 @@ public class BuildResultService {
else else
bcalsum=true; bcalsum=true;
sumobj.setNo(no).setDimId(fetchParam.getDimValue()).setDimName("合计"); sumobj.setNo(no).setDimId(fetchParam.getDimValue()).setDimName((bcalsum||fetchParam.getDimItem()==null)?"合计":fetchParam.getDimItem().getLabel());
for(DAMetric metric:fetchParam.getMetrics().values()) for(DAMetric metric:fetchParam.getMetrics().values())
{ {
sumobj.setVal(metric.getMetricId(),BigDecimal.ZERO); sumobj.setVal(metric.getMetricId(),BigDecimal.ZERO);
...@@ -701,12 +717,18 @@ public class BuildResultService { ...@@ -701,12 +717,18 @@ public class BuildResultService {
} }
@Cacheable( value="dataAnalyse",key="'rows:cg:'+#p0.getId()")
public FetchResult getReportConfig(FetchParam fetchParam)
{
prepareFetchParam(fetchParam);
return FetchResult.from(fetchParam);
}
@Cacheable( value="dataAnalyse",key="'rows:ar:'+#p0.getId()") @Cacheable( value="dataAnalyse",key="'rows:ar:'+#p0.getId()")
public FetchResult getAnalyseResult(FetchParam fetchParam) public FetchResult getAnalyseResult(FetchParam fetchParam)
{ {
List<FetchItem> rows = this.getResult(fetchParam); List<FetchItem> rows = this.getResult(fetchParam);
return FetchResult.from(fetchParam).setRows(rows); return FetchResult.from(fetchParam).setRows(rows).setSnapId(fetchParam.getId()).setSnapTime(new Timestamp(System.currentTimeMillis()));
} }
@CacheEvict( value = "dataAnalyse",allEntries = true) @CacheEvict( value = "dataAnalyse",allEntries = true)
...@@ -714,4 +736,80 @@ public class BuildResultService { ...@@ -714,4 +736,80 @@ public class BuildResultService {
{ {
} }
public File exportExcel(FetchParam fetchParam) {
FetchResult result=proxy.getAnalyseResult(fetchParam);
Assert.notNull(result,"报表数据查询失败");
Map<String, Object> resultDataMap = new HashMap<String, Object>();
String headname = result.getTitle();// 报表名称
Timestamp starttime = result.getStartTime();// 查询开始时间
Timestamp endtime = result.getEndTime();// 查询结束时间
List<Map<String,String>> titleList = new ArrayList<Map<String,String>>();
{
Map<String, String> titleMap = new HashMap<String, String>();
titleMap.put("id", "report");
titleMap.put("pid", "0");
titleMap.put("content", headname);
titleMap.put("fieldName", "report");
titleList.add(titleMap);
}
{
Map<String, String> titleMap = new HashMap<String, String>();
titleMap.put("id", "filter");
titleMap.put("pid", "report");
titleMap.put("content", DataObject.dayFormat.format(result.getStartTime()).concat("到").concat(DataObject.dayFormat.format(result.getEndTime())));
titleMap.put("fieldName", "filter");
titleList.add(titleMap);
this.onHandleColumn(result.getHeaders(),titleList,"filter");
}
return this.onCreateExcelFile(titleList, result.getRows(), headname, headname+fetchParam.getId(), starttime, endtime);
}
public List<Map<String,String>> onHandleColumn(List<VMConfig> headers,List<Map<String,String>> columnDataList,String pid) {
if(columnDataList==null) columnDataList = new ArrayList<Map<String,String>>();
if(StringUtils.isEmpty(pid)) pid="0";
for(VMConfig col:headers){
Map<String,String> titleMap = new HashMap<String,String>();
String field = StringUtils.isEmpty(col.getField())? IdWorker.get32UUID():col.getField();
if(col.isHide()) continue;
titleMap.put("id", field);
titleMap.put("pid", pid);
titleMap.put("content",col.getHeaderName());
titleMap.put("fieldName", field);
columnDataList.add(titleMap);
if(!ObjectUtils.isEmpty(col.getChildren()))
onHandleColumn(col.getChildren(),columnDataList,field);
}
return columnDataList;
}
public File onCreateExcelFile(List<Map<String,String>> titleList, List<FetchItem> rowList, String headName, String fileName, Timestamp startTime, Timestamp endTime) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String strNowDate = simpleDateFormat.format(date);
String dirPath=System.getProperty("java.io.tmpdir") +"reportExcel" + File.separator + strNowDate + File.separator;
File dir=new File(dirPath);
if(!dir.exists())
dir.mkdirs();
String strFilePath = dirPath +fileName + ".xls";
ExcelTool excelTool = new ExcelTool("报表", 20, 20);
try {
excelTool.exportExcel(excelTool.columnTransformer(titleList, "id", "pid", "content", "fieldName", "0"), rowList, strFilePath, true, false);
} catch (Exception exception) {
exception.printStackTrace();
}
File file=new File(strFilePath);
if(file.exists())
return file;
return null;
}
} }
...@@ -15,6 +15,7 @@ import cn.ibizlab.core.lite.extensions.service.LiteDataCallback; ...@@ -15,6 +15,7 @@ import cn.ibizlab.core.lite.extensions.service.LiteDataCallback;
import cn.ibizlab.core.lite.extensions.service.LiteDataService; import cn.ibizlab.core.lite.extensions.service.LiteDataService;
import cn.ibizlab.core.lite.extensions.service.LiteModelService; import cn.ibizlab.core.lite.extensions.service.LiteModelService;
import cn.ibizlab.core.rule.domain.ExecLog; import cn.ibizlab.core.rule.domain.ExecLog;
import cn.ibizlab.core.rule.domain.RuleEngine;
import cn.ibizlab.core.rule.domain.RuleItem; import cn.ibizlab.core.rule.domain.RuleItem;
import cn.ibizlab.core.rule.service.IExecLogService; import cn.ibizlab.core.rule.service.IExecLogService;
import cn.ibizlab.core.rule.service.IRuleItemService; import cn.ibizlab.core.rule.service.IRuleItemService;
...@@ -35,6 +36,7 @@ import org.springframework.context.annotation.Lazy; ...@@ -35,6 +36,7 @@ import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.io.File; import java.io.File;
...@@ -123,10 +125,6 @@ public class DABuildExService extends DABuildServiceImpl { ...@@ -123,10 +125,6 @@ public class DABuildExService extends DABuildServiceImpl {
* @return * @return
*/ */
@Override @Override
@Caching( evict = {
@CacheEvict(value ={"dabuild","dabuilddims"}, key = "'row:'+#p0.buildId"),
@CacheEvict( value="dataAnalyse",allEntries = true)
})
public DABuild run(DABuild et) { public DABuild run(DABuild et) {
if(!StringUtils.isEmpty(et.getBuildId())) if(!StringUtils.isEmpty(et.getBuildId()))
{ {
...@@ -179,24 +177,10 @@ public class DABuildExService extends DABuildServiceImpl { ...@@ -179,24 +177,10 @@ public class DABuildExService extends DABuildServiceImpl {
public void processData(EngineMQMsg engineMQMsg){ public void processData(EngineMQMsg engineMQMsg){
DABuild et = get(engineMQMsg.getEngineId());
try{ try{
BaseRequest msg=new BaseRequest(); BaseRequest msg=proxy.getRequest(engineMQMsg.getEngineId(),engineMQMsg.getBatch()).copy(true);
msg.setId(IdWorker.getIdStr()); msg.setId(IdWorker.getIdStr());
msg.setModel(et.getModelName());
msg.setBatch(engineMQMsg.getBatch());
msg.setSystemid(et.getSystemId());
msg.setEngineId(engineMQMsg.getEngineId());
String resultDataSource = Setting.getValue(et.getExtParams(), "resultDataSource");
String resultTableName = Setting.getValue(et.getExtParams(), "resultTableName");
if(StringUtils.isEmpty(resultDataSource)){
resultDataSource=Default_ResultDataSource;
}
if(StringUtils.isEmpty(resultTableName)){
resultTableName=Default_ResultTableName;
}
msg.setResultDataSource(resultDataSource);
msg.setResultTableName(resultTableName);
ExecLog execlog=new ExecLog(); ExecLog execlog=new ExecLog();
execlog.setId(msg.getId()); execlog.setId(msg.getId());
...@@ -205,59 +189,7 @@ public class DABuildExService extends DABuildServiceImpl { ...@@ -205,59 +189,7 @@ public class DABuildExService extends DABuildServiceImpl {
execlog.setSystemId(msg.getSystemid()); execlog.setSystemId(msg.getSystemid());
ruExecLogService.create(execlog); ruExecLogService.create(execlog);
List<String> ruleIds = new ArrayList<>(); msg.setDatas(liteDataService.getModelObjs(msg.getModelId(),msg.getFillpropertys(),engineMQMsg.getDatas()));
List<String> rulePaths = new ArrayList<>();
DataModel dataModel=liteModelService.getDataModel(et.getModelId());
HashSet<String> fillpropertys=new HashSet<>();
List<String> metrics = new ArrayList<>();
idaMetricService.list(Wrappers.<DAMetric>lambdaQuery().eq(DAMetric::getBuildId,et.getBuildId()))
.forEach(daMetric -> {
metrics.add(daMetric.getMetricId());
});
if(metrics.size() == 0){
log.error(String.format("构建数据失败:未配置指标"));
return;
}
ruleItemService.list(Wrappers.<RuleItem>lambdaQuery().in(RuleItem::getRuleId, metrics))
.forEach(ruleItem -> {
String path=rulePath + ruleItem.getGroup() + File.separator + ruleItem.getRuleId() + ".drl";
File file=new File(path);
if(!file.exists())
{
ruleItemService.buildRuleFile(ruleItem);
}
if(file.exists())
{
rulePaths.add(path);
ruleIds.add(ruleItem.getRuleId());
}
if((!StringUtils.isEmpty(ruleItem.getCond()))&&ruleItem.getCond().startsWith("["))
fillpropertys.addAll(JSON.toJavaObject(JSON.parseArray(ruleItem.getCond()), LinkedHashSet.class));
});
if(ruleIds.size() == 0){
log.error(String.format("构建数据失败:无有效规则"));
return;
}
dataModel.getAllProperty().forEach(prop->{
if(fillpropertys.contains(prop.getPropertyName()))
{
DataModel p=prop.getOwnerDataModel().getParentDataModel();
while (p!=null)
{
fillpropertys.add(p.getFactPorperty().getPropertyName());
p=p.getParentDataModel();
}
}
});
msg.setRuleIds(ruleIds);
msg.setRules(rulePaths);
msg.setDatas(liteDataService.getModelObjs(et.getModelId(),fillpropertys,engineMQMsg.getDatas()));
analyseEntityServiceImpl.processAll(msg); analyseEntityServiceImpl.processAll(msg);
...@@ -273,8 +205,110 @@ public class DABuildExService extends DABuildServiceImpl { ...@@ -273,8 +205,110 @@ public class DABuildExService extends DABuildServiceImpl {
param.put("runtime", engineMQMsg.getRunTime()); param.put("runtime", engineMQMsg.getRunTime());
param.put("engineId", engineMQMsg.getEngineId()); param.put("engineId", engineMQMsg.getEngineId());
this.execute(updateSql, param); this.execute(updateSql, param);
if(this.count(Wrappers.<DABuild>lambdaQuery().eq(DABuild::getBuildId,engineMQMsg.getEngineId()).eq(DABuild::getState,"FINISH"))==1)
{
proxy.resetRequest(engineMQMsg.getEngineId(),engineMQMsg.getBatch());
proxy.resetBuild(engineMQMsg.getEngineId());
proxy.resetDataAnalyseResult();
}
}
@Cacheable(value ="dabuild", key = "'batch:'+#p0+#p1")
public BaseRequest getRequest(String id,String batch)
{
DABuild et = get(id);
BaseRequest msg=new BaseRequest();
msg.setModelId(et.getModelId());
msg.setModel(et.getModelName());
msg.setBatch(batch);
msg.setSystemid(et.getSystemId());
msg.setEngineId(id);
String resultDataSource = Setting.getValue(et.getExtParams(), "resultDataSource");
String resultTableName = Setting.getValue(et.getExtParams(), "resultTableName");
if(StringUtils.isEmpty(resultDataSource)){
resultDataSource=Default_ResultDataSource;
}
if(StringUtils.isEmpty(resultTableName)){
resultTableName=Default_ResultTableName;
}
msg.setResultDataSource(resultDataSource);
msg.setResultTableName(resultTableName);
List<String> ruleIds = new ArrayList<>();
List<String> rulePaths = new ArrayList<>();
DataModel dataModel=liteModelService.getDataModel(et.getModelId());
HashSet<String> fillpropertys=new HashSet<>();
List<String> metrics = new ArrayList<>();
idaMetricService.list(Wrappers.<DAMetric>lambdaQuery().eq(DAMetric::getBuildId,et.getBuildId()))
.forEach(daMetric -> {
metrics.add(daMetric.getMetricId());
});
Assert.notEmpty(metrics,"构建数据失败:未配置指标");
ruleItemService.list(Wrappers.<RuleItem>lambdaQuery().in(RuleItem::getRuleId, metrics))
.forEach(ruleItem -> {
String path=rulePath + ruleItem.getGroup() + File.separator + ruleItem.getRuleId() + ".drl";
File file=new File(path);
if(!file.exists())
{
ruleItemService.buildRuleFile(ruleItem);
}
if(file.exists())
{
rulePaths.add(path);
ruleIds.add(ruleItem.getRuleId());
}
if((!StringUtils.isEmpty(ruleItem.getCond()))&&ruleItem.getCond().startsWith("["))
fillpropertys.addAll(JSON.toJavaObject(JSON.parseArray(ruleItem.getCond()), LinkedHashSet.class));
});
Assert.notEmpty(ruleIds,"构建数据失败:无有效规则");
dataModel.getAllProperty().forEach(prop->{
if(fillpropertys.contains(prop.getPropertyName()))
{
DataModel p=prop.getOwnerDataModel().getParentDataModel();
while (p!=null)
{
fillpropertys.add(p.getFactPorperty().getPropertyName());
p=p.getParentDataModel();
}
}
});
msg.setFillpropertys(fillpropertys);
msg.setRuleIds(ruleIds);
msg.setRules(rulePaths);
return msg;
} }
@CacheEvict(value ="dabuild", key = "'batch:'+#p0+#p1")
public void resetRequest(String id,String batch)
{
}
@CacheEvict( value="dataAnalyse",allEntries = true)
public void resetDataAnalyseResult()
{
}
@CacheEvict(value ={"dabuild","dabuilddims"}, key = "'row:'+#p0")
public void resetBuild(String id)
{
}
@Autowired
@Lazy
DABuildExService proxy;
@Cacheable(value ="dabuilddims", key = "'row:'+#p0") @Cacheable(value ="dabuilddims", key = "'row:'+#p0")
public List<DADimension> getDims(String id) public List<DADimension> getDims(String id)
...@@ -282,6 +316,7 @@ public class DABuildExService extends DABuildServiceImpl { ...@@ -282,6 +316,7 @@ public class DABuildExService extends DABuildServiceImpl {
return this.get(id).getDadimension(); return this.get(id).getDadimension();
} }
@Override @Override
@Transactional @Transactional
@CacheEvict(value ={"dabuild","dabuilddims"}, key = "'row:'+#p0.buildId") @CacheEvict(value ={"dabuild","dabuilddims"}, key = "'row:'+#p0.buildId")
......
...@@ -23,6 +23,8 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers; ...@@ -23,6 +23,8 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -133,24 +135,10 @@ public class RuleEngineExService extends RuleEngineServiceImpl { ...@@ -133,24 +135,10 @@ public class RuleEngineExService extends RuleEngineServiceImpl {
protected IExecLogService ruExecLogService; protected IExecLogService ruExecLogService;
public void processData(EngineMQMsg engineMQMsg){ public void processData(EngineMQMsg engineMQMsg){
RuleEngine et = get(engineMQMsg.getEngineId());
try{ try{
BaseRequest msg=new BaseRequest(); BaseRequest msg=proxy.getRequest(engineMQMsg.getEngineId(),engineMQMsg.getBatch()).copy(true);
msg.setId(IdWorker.getIdStr()); msg.setId(IdWorker.getIdStr());
msg.setModel(et.getModelName());
msg.setBatch(engineMQMsg.getBatch());
msg.setSystemid(et.getSystemId());
msg.setEngineId(engineMQMsg.getEngineId());
String resultDataSource = Setting.getValue(et.getExtParams(), "resultDataSource");
String resultTableName = Setting.getValue(et.getExtParams(), "resultTableName");
if(StringUtils.isEmpty(resultDataSource)){
resultDataSource=Default_ResultDataSource;
}
if(StringUtils.isEmpty(resultTableName)){
resultTableName=Default_ResultTableName;
}
msg.setResultDataSource(resultDataSource);
msg.setResultTableName(resultTableName);
ExecLog execlog=new ExecLog(); ExecLog execlog=new ExecLog();
execlog.setId(msg.getId()); execlog.setId(msg.getId());
...@@ -158,43 +146,7 @@ public class RuleEngineExService extends RuleEngineServiceImpl { ...@@ -158,43 +146,7 @@ public class RuleEngineExService extends RuleEngineServiceImpl {
execlog.setKeyValueField(msg.getModel()); execlog.setKeyValueField(msg.getModel());
execlog.setSystemId(msg.getSystemid()); execlog.setSystemId(msg.getSystemid());
ruExecLogService.create(execlog); ruExecLogService.create(execlog);
msg.setDatas(liteDataService.getModelObjs(msg.getModelId(),msg.getFillpropertys(),engineMQMsg.getDatas()));
List<String> rules = new ArrayList<>();
DataModel dataModel=liteModelService.getDataModel(et.getModelId());
HashSet<String> fillpropertys=new HashSet<>();
ruleItemService.list(Wrappers.<RuleItem>lambdaQuery()
.eq(RuleItem::getModelId,et.getModelId()).ne(RuleItem::getGroup,"REP").like(RuleItem::getGroup,et.getGroup()))
.forEach(ruleItem -> {
String path=rulePath + et.getGroup() + File.separator + ruleItem.getRuleId() + ".drl";
File file=new File(path);
if(!file.exists())
{
ruleItemService.buildRuleFile(ruleItem);
}
if(file.exists())
{
rules.add(path);
}
if((!StringUtils.isEmpty(ruleItem.getCond()))&&ruleItem.getCond().startsWith("["))
fillpropertys.addAll(JSON.toJavaObject(JSON.parseArray(ruleItem.getCond()),LinkedHashSet.class));
});
dataModel.getAllProperty().forEach(prop->{
if(fillpropertys.contains(prop.getPropertyName()))
{
DataModel p=prop.getOwnerDataModel().getParentDataModel();
while (p!=null)
{
fillpropertys.add(p.getFactPorperty().getPropertyName());
p=p.getParentDataModel();
}
}
});
msg.setRules(rules);
msg.setDatas(liteDataService.getModelObjs(et.getModelId(),fillpropertys,engineMQMsg.getDatas()));
baseEntityService.processAll(msg); baseEntityService.processAll(msg);
}catch (Exception ex){ }catch (Exception ex){
...@@ -209,7 +161,79 @@ public class RuleEngineExService extends RuleEngineServiceImpl { ...@@ -209,7 +161,79 @@ public class RuleEngineExService extends RuleEngineServiceImpl {
param.put("runtime", engineMQMsg.getRunTime()); param.put("runtime", engineMQMsg.getRunTime());
param.put("engineId", engineMQMsg.getEngineId()); param.put("engineId", engineMQMsg.getEngineId());
this.execute(updateSql, param); this.execute(updateSql, param);
if(this.count(Wrappers.<RuleEngine>lambdaQuery().eq(RuleEngine::getEngineId,engineMQMsg.getEngineId()).eq(RuleEngine::getState,"FINISH"))==1)
{
proxy.resetRequest(engineMQMsg.getEngineId(),engineMQMsg.getBatch());
}
} }
@Autowired
@Lazy
RuleEngineExService proxy;
@Cacheable(value ="ruleengine", key = "'batch:'+#p0+#p1")
public BaseRequest getRequest(String id,String batch)
{
RuleEngine et = get(id);
BaseRequest msg=new BaseRequest();
msg.setModelId(et.getModelId());
msg.setModel(et.getModelName());
msg.setBatch(batch);
msg.setSystemid(et.getSystemId());
msg.setEngineId(id);
String resultDataSource = Setting.getValue(et.getExtParams(), "resultDataSource");
String resultTableName = Setting.getValue(et.getExtParams(), "resultTableName");
if(StringUtils.isEmpty(resultDataSource)){
resultDataSource=Default_ResultDataSource;
}
if(StringUtils.isEmpty(resultTableName)){
resultTableName=Default_ResultTableName;
}
msg.setResultDataSource(resultDataSource);
msg.setResultTableName(resultTableName);
List<String> rules = new ArrayList<>();
DataModel dataModel=liteModelService.getDataModel(et.getModelId());
HashSet<String> fillpropertys=new HashSet<>();
ruleItemService.list(Wrappers.<RuleItem>lambdaQuery()
.eq(RuleItem::getModelId,et.getModelId()).ne(RuleItem::getGroup,"REP").like(RuleItem::getGroup,et.getGroup()))
.forEach(ruleItem -> {
String path=rulePath + et.getGroup() + File.separator + ruleItem.getRuleId() + ".drl";
File file=new File(path);
if(!file.exists())
{
ruleItemService.buildRuleFile(ruleItem);
}
if(file.exists())
{
rules.add(path);
}
if((!StringUtils.isEmpty(ruleItem.getCond()))&&ruleItem.getCond().startsWith("["))
fillpropertys.addAll(JSON.toJavaObject(JSON.parseArray(ruleItem.getCond()),LinkedHashSet.class));
});
dataModel.getAllProperty().forEach(prop->{
if(fillpropertys.contains(prop.getPropertyName()))
{
DataModel p=prop.getOwnerDataModel().getParentDataModel();
while (p!=null)
{
fillpropertys.add(p.getFactPorperty().getPropertyName());
p=p.getParentDataModel();
}
}
});
msg.setRules(rules);
msg.setFillpropertys(fillpropertys);
return msg;
}
@CacheEvict(value ="ruleengine", key = "'batch:'+#p0+#p1")
public void resetRequest(String id,String batch)
{
}
/** /**
* [Check:校验] 行为扩展 * [Check:校验] 行为扩展
* @param et * @param et
......
package cn.ibizlab.core.extensions.util;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* excel处理工具
* 概念-> 表头数据:报表的表头
* 行内数据:表头以下的数据
* 功能:动态生成单级,多级Excel表头
* 备注:tree型结构数据的root节点的id必须为零(0)
* Created by wtj on 2018/3/2.
* 修改:
* 2019/03/18 修复生成跨列的bug
* 2019/03/20 修复集合存在root的时候,生成不了动态表头
* @param <T>
*/
public class ExcelTool<T> {
private HSSFWorkbook workbook;//excel 对象
private String title; //表格标题
private int colWidth = 20; //单元格宽度
private int rowHeight = 20;//单元格行高度
private HSSFCellStyle styleHead; //表头样式
private HSSFCellStyle styleBody; //主体样式
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //日期格式化,默认yyyy-MM-dd HH:mm:ss
/**
* 无参数 初始化 对象
*/
public ExcelTool(){
this.title="sheet1";
this.workbook = new HSSFWorkbook();
init(0);
}
/**
* 有参数 初始化 对象
* @param title
* @param colWidth
* @param rowHeight
* @param dateFormat
*/
public ExcelTool(String title,int colWidth,int rowHeight,String dateFormat){
this.colWidth = colWidth;
this.rowHeight = rowHeight;
this.title = title;
this.workbook = new HSSFWorkbook();
this.sdf = new SimpleDateFormat(dateFormat);
init(0);
}
public ExcelTool(String title,int colWidth,int rowHeight){
this.colWidth = colWidth;
this.rowHeight = rowHeight;
this.title = title;
this.workbook = new HSSFWorkbook();
init(0);
}
public ExcelTool(String title,int colWidth,int rowHeight,int flag){
this.colWidth = colWidth;
this.rowHeight = rowHeight;
this.title = title;
this.workbook = new HSSFWorkbook();
init(flag);
}
public ExcelTool(String title){
this.title = title;
this.workbook = new HSSFWorkbook();
init(0);
}
/**ExcelTool 属性 get、set 方法 开始*/
public int getColWidth() {
return colWidth;
}
public void setColWidth(int colWidth) {
this.colWidth = colWidth;
}
public int getRowHeight() {
return rowHeight;
}
public void setRowHeight(int rowHeight) {
this.rowHeight = rowHeight;
}
public HSSFWorkbook getWorkbook() {
return this.workbook;
}
public void setWorkbook(HSSFWorkbook workbook) {
this.workbook = workbook;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public HSSFCellStyle getStyleHead() {
return styleHead;
}
public void setStyleHead(HSSFCellStyle styleHead) {
this.styleHead = styleHead;
}
public HSSFCellStyle getStyleBody() {
return styleBody;
}
public void setStyleBody(HSSFCellStyle styleBody) {
this.styleBody = styleBody;
}
/**ExcelTool 属性 get、set 方法 结束*/
//内部统一调用的样式初始化
private void init(int styleFlag){
this.styleHead = this.workbook.createCellStyle();
this.styleHead.setAlignment(HorizontalAlignment.CENTER);// 左右居中
this.styleHead.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
this.styleHead.setRightBorderColor(HSSFColor.BLACK.index);
this.styleHead.setBottomBorderColor(HSSFColor.BLACK.index);
this.styleHead.setWrapText(true);// 表头自动换行
switch(styleFlag){
case 1:
this.styleBody = this.workbook.createCellStyle();
this.styleBody.setAlignment(HorizontalAlignment.CENTER);// 左右居中ALIGN_CENTER
this.styleBody.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
this.styleBody.setRightBorderColor(HSSFColor.BLACK.index);
this.styleBody.setBottomBorderColor(HSSFColor.BLACK.index);
this.styleBody.setBorderRight(BorderStyle.THIN);// 边框的大小
this.styleBody.setBorderBottom(BorderStyle.THIN);// 边框的大小
break;
default:
this.styleBody = this.workbook.createCellStyle();
this.styleBody.setAlignment(HorizontalAlignment.CENTER);// 左右居中ALIGN_CENTER
this.styleBody.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
this.styleBody.setRightBorderColor(HSSFColor.BLACK.index);
this.styleBody.setBottomBorderColor(HSSFColor.BLACK.index);
this.styleBody.setBorderRight(BorderStyle.THIN);// 边框的大小
this.styleBody.setBorderBottom(BorderStyle.THIN);// 边框的大小
break;
}
}
/**
* 导出表格 无返回
* @param listTpamscolumn 表头数据
* @param datas 行内数据
* @param FilePath 保存路径
* @param flag
* @param rowFlag
* @throws Exception
*/
public void exportExcel(List<Column> listTpamscolumn, List<T> datas, String FilePath, boolean flag, boolean rowFlag) throws Exception{
splitDataToSheets(datas, listTpamscolumn,flag,rowFlag);
// this.workbook.getSheet("报表1").autoSizeColumn(1, true);
save(this.workbook,FilePath);
}
/**
* 返回workbook
* @param listTpamscolumn 表头数据
* @param datas 行内数据
* @param flag 是否写入行内数据
* @return
* @throws Exception
*/
public HSSFWorkbook exportWorkbook(List<Column> listTpamscolumn, List<T> datas , boolean flag) throws Exception{
splitDataToSheets(datas, listTpamscolumn,flag,false);
return this.workbook;
}
/**
* 导出表格 有返回值
* @param listTpamscolumn 表头数据
* @param datas 行内数据
* @param flag 只输出表头数据
* @param rowFlag
* @return
* @throws Exception
*/
public InputStream exportExcel(List<Column> listTpamscolumn, List<T> datas, boolean flag, boolean rowFlag) throws Exception {
splitDataToSheets(datas, listTpamscolumn,flag,rowFlag);
return save(this.workbook);
}
/**
* 导出Excel,适用于web导出excel
* @param sheet excel
* @param data 行内数据
* @param listTpamscolumn 表头数据
* @param flag 只输出表头数据
* @param rowFlag 输出展示数据的结构(表头下面行的数据)
* @throws Exception
*/
private void writeSheet(HSSFSheet sheet, List<T> data, List<Column> listTpamscolumn, boolean flag, boolean rowFlag) throws Exception {
sheet.setDefaultColumnWidth(colWidth);
sheet.setDefaultRowHeightInPoints(rowHeight);
sheet = createHead(sheet, listTpamscolumn.get(0).getTotalRow(), listTpamscolumn.get(0).getTotalCol());
createHead(listTpamscolumn,sheet,0);
if(flag)//控制是否 bug修复:每次写入行数据时,总是漏第一个条数据 rowIndex 错误
writeSheetContent(listTpamscolumn,data,sheet, listTpamscolumn.get(0).getTotalRow()+1,rowFlag);
}
/**
* 拆分sheet,因为每个sheet不能超过65535,否则会报异常
* @param data 行内数据
* @param listTpamscolumn 表头数据
* @param flag 只输出表头数据
* @param rowFlag 输出展示数据的结构(表头下面行的数据)
* @throws Exception
*/
private void splitDataToSheets(List<T> data, List<Column> listTpamscolumn, boolean flag, boolean rowFlag)throws Exception{
int dataCount = data.size();
int maxColumn = 65535;
int pieces = dataCount/maxColumn;
for(int i = 1; i <= pieces;i++){
HSSFSheet sheet = this.workbook.createSheet(this.title+i);
List<T> subList = data.subList((i-1)*maxColumn, i*maxColumn);
writeSheet(sheet,subList, listTpamscolumn,flag,rowFlag);
}
HSSFSheet sheet = this.workbook.createSheet(this.title+(pieces+1));
writeSheet(sheet, data.subList(pieces*maxColumn, dataCount), listTpamscolumn,flag,rowFlag);
}
/**
* 把数据写入到单元格
* @param listTpamscolumn 表头数据
* @param datas 行内数据
* @param sheet 工作表(excel分页)
* @throws Exception
* void
*/
private void writeSheetContent(List<Column> listTpamscolumn, List<T> datas, HSSFSheet sheet, int rowIndex, boolean rowFlag) throws Exception{
HSSFRow row = null;
List<Column> listCol=new ArrayList<>();
rowFlag=false;
if(rowFlag){//暂时没有用 后面扩展用
for (int i = 0, index = rowIndex; i < datas.size(); i++, index++) {
row = sheet.createRow(index);//创建行
for (int j = 0; j < listTpamscolumn.size(); j++) {
createColl(row,j,listTpamscolumn.get(j).getFieldName() ,datas.get(i));
}
}
}
else {
getColumnList(listTpamscolumn, listCol);
for (int i = 0, index = rowIndex; i < datas.size(); i++, index++) {
row = sheet.createRow(index);//创建行
for (int j = 0; j < listCol.size(); j++) {
Column c = listCol.get(j);
createCol(row, c, datas.get(i));
}
}
}
}
/**
* 根据list 来创建单元格 暂时没有用
* @param row
* @param j
* @param finame
* @param t
*/
private void createColl(HSSFRow row, int j, String finame, T t) {
HSSFCell cell = row.createCell(j); //创建单元格
cell.setCellStyle(this.styleBody); //设置单元格样式
String text="";
if(t instanceof List){
List<Map> temp= (List<Map>)t;
if(j>=temp.size()) return;
text=String.valueOf( temp.get(j).get(finame)==null?"": temp.get(j).get(finame));
}
HSSFRichTextString richString = new HSSFRichTextString(text);
cell.setCellValue(richString);
}
/**
* 把column的columnList整理成一个list<column> 过滤表头的脏数据
* @param list 表头数据
* @param listCol 返回新的list
* @return
* List<column>
*/
private void getColumnList(List<Column> list, List<Column> listCol){
for(int i = 0; i < list.size(); i++){
if(list.get(i).getFieldName() != null){
listCol.add(list.get(i));
}
List<Column> listChilren = list.get(i).getListTpamscolumn();
if(listChilren.size() > 0){
getColumnList( listChilren, listCol);
}
}
}
/**
* 保存Excel到InputStream,此方法适合web导出excel
* @param workbook
* @return
*/
private InputStream save(HSSFWorkbook workbook) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
workbook.write(bos);
InputStream bis = new ByteArrayInputStream(bos.toByteArray());
return bis;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 保存excel到本机指定的路径
* @param workbook
* @param filePath
* @throws IOException
*/
private void save(HSSFWorkbook workbook, String filePath){
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
workbook.write(fOut);
fOut.flush();
} catch (Exception e) {
e.printStackTrace();
}
try {if(null!=fOut) fOut.close();} catch (Exception e1) { }
}
/**
* 创建行
* @param row Excel对应的行
* @param tpamscolumn 当前单元格属性
* @param v
* @param j
* @return
* @throws Exception
*/
public int createRowVal(HSSFRow row, Column tpamscolumn, T v, int j) throws Exception{
//遍历标题
if(tpamscolumn.getListTpamscolumn() != null && tpamscolumn.getListTpamscolumn().size() > 0){
for(int i = 0; i < tpamscolumn.getListTpamscolumn().size(); i++){
createRowVal(row, tpamscolumn.getListTpamscolumn().get(i),v,j);
}
}else{
createCol(row, tpamscolumn,v);
}
return j;
}
/**
* 创建单元格
* @param row Excel对应的行
* @param tpamscolumn 当前单元格对象
* @param v
* @throws Exception
*/
public void createCol(HSSFRow row, Column tpamscolumn, T v) throws Exception{
HSSFCell cell = row.createCell( tpamscolumn.getCol()); //创建单元格
cell.setCellStyle(this.styleBody); //设置单元格样式
final Object[] value = {null};
if(v instanceof Map){
Map m=(Map)v;
m.forEach((k, val) -> {
if(k.equals(tpamscolumn.getFieldName()) && !tpamscolumn.isHasChilren()){
value[0] =val;
}
});
}else {
Class<?> cls = v.getClass();// 拿到该类
Field[] fields=cls.getDeclaredFields();// 获取实体类的所有属性,返回Field数组
for(int i=0;i<fields.length;i++){
Field f = fields[i];
f.setAccessible(true); // 设置些属性是可以访问的
if(tpamscolumn.getFieldName().equals(f.getName()) && !tpamscolumn.isHasChilren() )// && !tpamscolumn.isHasChilren()
value[0] = f.get(v);
if(value[0] instanceof Date)
value[0] = parseDate((Date) value[0]);
}
}
if(value[0]!=null) {
HSSFRichTextString richString = new HSSFRichTextString(value[0].toString());
cell.setCellValue(richString);
}
}
/**
* 时间转换
* @param date
* @return
* String
*/
private String parseDate(Date date){
String dateStr = "";
try{
dateStr = this.sdf.format(date);
} catch (Exception e){
e.printStackTrace();
}
return dateStr;
}
/**
* 根据数据的行数和列数,在excel创建单元格cell
* @param sheetCo excel分页
* @param r excel 行数
* @param c excel 列数
* @return
*/
public HSSFSheet createHead(HSSFSheet sheetCo, int r, int c){
for(int i = 0; i <r; i++){
HSSFRow row = sheetCo.createRow(i);
for(int j = 0; j <c; j++){
HSSFCell cell=row.createCell(j);
}
}
return sheetCo;
}
/**
* 使用递归 在excel写入表头数据 支持单级,多级表头的创建
* @param listTpamscolumn 表头数据
* @param sheetCo 哪个分页
* @param rowIndex 当前Excel的第几行
*/
public void createHead(List<Column> listTpamscolumn, HSSFSheet sheetCo, int rowIndex){
HSSFRow row = sheetCo.getRow(rowIndex);
// if(row == null)row = sheetCo.createRow(rowIndex);
int len = listTpamscolumn.size();//当前行 有多少列
for(int i = 0; i <len; i++){//i是headers的索引,n是Excel的索引 多级表头
Column tpamscolumn = listTpamscolumn.get(i);
//创建这一行的第几列单元格
int r = tpamscolumn.getRow();
int rLen = tpamscolumn.getrLen();
int c = tpamscolumn.getCol();
int cLen = tpamscolumn.getcLen();
int endR = r+rLen;
int endC = c+cLen;
if(endC > c){
endC--;
}
HSSFCell cell = row.getCell(c);
// if( null == cell)cell = row.createCell(c);
HSSFRichTextString text = new HSSFRichTextString(tpamscolumn.getContent());
cell.setCellStyle(this.styleHead); //设置表头样式
cell.setCellValue(text);
// 合并单元格
CellRangeAddress cra = new CellRangeAddress(r,endR,c,endC);
sheetCo.addMergedRegion(cra);
// 使用RegionUtil类为合并后的单元格添加边框
RegionUtil.setBorderBottom(BorderStyle.THIN, cra,sheetCo); // 下边框
RegionUtil.setBorderLeft(BorderStyle.THIN, cra,sheetCo); // 左边框
RegionUtil.setBorderRight(BorderStyle.THIN, cra,sheetCo); // 有边框
if(tpamscolumn.isHasChilren()){
rowIndex=r+1;
createHead( tpamscolumn.getListTpamscolumn(), sheetCo,rowIndex);
}
}
}
/**
* 转换成column对象
* 支持List<T>的数据结构:map String ,只能是单级的数据
* @param list 需要转换的数据
* @return
*/
public List<Column> columnTransformer(List<T> list){
List<Column> lc=new ArrayList<>();
if(list.get(0)instanceof Map) {
final int[] i = {1};
for (Map<String, String> m :(List<Map<String, String>>)list ) {
m.forEach((k, val) -> {
Column tpamscolumn = new Column();
tpamscolumn.setId(String.valueOf(i[0]));
tpamscolumn.setPid("0");
tpamscolumn.setContent(k);
tpamscolumn.setFieldName(val);
lc.add(tpamscolumn);
i[0]++;
});
}
} else {
int i = 1;
for(String s:(List<String>)list) {
Column tpamscolumn = new Column();
tpamscolumn.setId(String.valueOf(i));
tpamscolumn.setPid("0");
tpamscolumn.setContent(s);
tpamscolumn.setFieldName(null);
lc.add(tpamscolumn);
i++;
}
}
setParm(lc,"0");//处理一下
List<Column> s = TreeTool.buildByRecursive(lc,"0");
setColNum(lc,s,s);
return s;
}
/**
* 转换成column对象 返回tree数据结构
* 支持:List<map>、某个具体对象(entity)数据的转换
* @param list 需要转换的数据
* @param id 当前节点id 字段的名称 主键
* @param pid 父节点id 字段的名称
* @param content 填写表头单元格内容的 字段名称
* @param fieldName 填写行内数据对的 字段名称
* @param rootid rootid的值
* @return
* @throws Exception
*/
public List<Column> columnTransformer(List<T> list , String id, String pid, String content, String fieldName,String rootid) throws Exception {
List<Column> lc=new ArrayList<>();
if(list.get(0) instanceof Map){
for(Map m:(List<Map>)list) {
Column tpamscolumn = new Column();
m.forEach((k, val) -> {//java8 以上的遍历方式
if (id.equals(k))
tpamscolumn.setId(String.valueOf(val));
if (pid.equals(k)) tpamscolumn.setPid((String) val);
if (content.equals(k)) tpamscolumn.setContent((String) val);
if (fieldName.equals(k) && fieldName != null) tpamscolumn.setFieldName((String) val);
});
lc.add(tpamscolumn);
}
}else {
for (T t : list) {//反射
Column tpamscolumn = new Column();
Class cls = t.getClass();
Field[] fs=cls.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
f.setAccessible(true); // 设置些属性是可以访问的
if (id.equals(f.getName()) && f.get(t) != null)
tpamscolumn.setId(f.get(t).toString());
if (pid.equals(f.getName()) && f.get(t) != null)
tpamscolumn.setPid(f.get(t).toString());
// if (pid.equals(f.getName()) && ( f.get(t) == null || "".equals(f.get(t)))) tpamscolumn.setPid("0");
if (content.equals(f.getName()) && f.get(t) != null)
tpamscolumn.setContent(f.get(t).toString());
if ( f.get(t) != null && fieldName!=null && fieldName.equals(f.getName()))
tpamscolumn.setFieldName(f.get(t).toString());
}
lc.add(tpamscolumn);
}
}
setParm(lc,rootid);//处理一下
List<Column> s = TreeTool.buildByRecursive(lc,rootid);
setColNum(lc,s,s);
return s;
}
/**
* 设置基础的参数
* @param list
*/
public static void setParm(List<Column> list,String rootid){
int row = 0;//excel第几行
int rLen = 0; //excel 跨多少行
int totalRow = TreeTool.getMaxStep(list);
int totalCol = TreeTool.getDownChilren(list,rootid);
for(int i=0;i<list.size();i++){
Column poit= list.get(i);
int tree_step = TreeTool.getTreeStep(list,poit.getPid(),0);//往上遍历tree
poit.setTree_step(tree_step);
poit.setRow(tree_step);//设置第几行
//判断是否有节点
boolean hasCh = TreeTool.hasChild( list,poit);
poit.setHasChilren(hasCh);
if(hasCh){
poit.setrLen(0);//设置跨多少行
}else{
if(tree_step < totalRow){
rLen = totalRow - tree_step;
}
poit.setrLen(rLen);
}
// boolean flag=false;//控制只有root 节点才有总的行数信息
// if(rootid == null && rootid == poit.getId() )flag = true;
// if(rootid != null && rootid.equals(poit.getId()))flag = true;
// if(flag){
//
// }
poit.setTotalRow(totalRow);
poit.setTotalCol(totalCol);
}
}
/**
* 设置基础的参数
* @param list 所有list数据,一条一条
* @param treeList 转成tree结构的list
*/
public static void setColNum(List<Column> list, List<Column> treeList,List<Column> flist){
// int col = pcIndex;//excel第几列
// int cLen ;//xcel跨多少列
List<Column> new_list = new ArrayList<>();//新的遍历list
for(int i = 0;i < treeList.size();i++){
Column poit= treeList.get(i);
// String temp_id = TreeTool.getStepFid(list,poit.getId() ,1);
int col = TreeTool.getFCol(list,poit.getPid()).getCol();
int brotherCol = TreeTool.getBrotherChilNum(list,poit);
poit.setCol(col+brotherCol);
int cLen = TreeTool.getDownChilren(list,poit.getId());
if(cLen<=1)cLen=0;
// else cLen--;
poit.setcLen(cLen);//设置跨多少列
if(poit.getListTpamscolumn().size()>0){
new_list.addAll(poit.getListTpamscolumn());
}
}
if(new_list.size() > 0){
setColNum( list,new_list,flist);
}
}
//========上部分是导出excel的使用(生成excel),下部分是解析excel,由于excel导入==================================================================================================================================
/**
* 根据HSSFCell类型设置数据
* @param cell 单元格
* @return
*/
public static String getCellFormatValue(Cell cell) {
String cellvalue = "";
if (cell != null) {
switch (cell.getCellType()) { // 判断当前Cell的Type
case HSSFCell.CELL_TYPE_NUMERIC: // 如果当前Cell的Type为NUMERIC
case HSSFCell.CELL_TYPE_FORMULA: {
// 判断当前的cell是否为Date
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
cellvalue = sdf.format(date);
}
else { // 如果是纯数字
cellvalue = String.valueOf(cell.getNumericCellValue());
}
break;
}
case HSSFCell.CELL_TYPE_STRING: // 如果当前Cell的Type为STRIN
// 取得当前的Cell字符串
cellvalue = cell.getRichStringCellValue().getString();
break;
default: // 默认的Cell值
cellvalue = "";
}
} else {
cellvalue = "";
}
return cellvalue;
}
/**
* 描述:根据文件后缀,自适应上传文件的版本
* @param inStr,fileName
* @return
* @throws Exception
*/
public static Workbook getWorkbookType(InputStream inStr, String fileName) throws Exception{
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if(".xls".equals(fileType)){
wb = new HSSFWorkbook(inStr); //2003-
}else if(".xlsx".equals(fileType)){
wb = new XSSFWorkbook(inStr); //2007+
}else{
throw new Exception("导入格式错误");
}
return wb;
}
/**
* 获取单元格数据内容为字符串类型的数据
* @param cell Excel单元格
* @return String 单元格数据内容
*/
public static String getStringCellValue(Cell cell) {
String strCell = "";
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
strCell = cell.getStringCellValue().trim();
break;
case Cell.CELL_TYPE_NUMERIC:
strCell = String.valueOf(cell.getNumericCellValue()).trim();
break;
case Cell.CELL_TYPE_BOOLEAN:
strCell = String.valueOf(cell.getBooleanCellValue()).trim();
break;
case Cell.CELL_TYPE_BLANK:
strCell = "";
break;
default:
strCell = "";
break;
}
if (strCell.equals("") || strCell == null) {
return "";
}
return strCell;
}
/**
* 判断指定的单元格是否是合并单元格
* @param sheet
* @param row 行下标
* @param column 列下标
* @return
*/
public boolean isMergedRegion(Sheet sheet, int row, int column) {
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress range = sheet.getMergedRegion(i);
int firstColumn = range.getFirstColumn();
int lastColumn = range.getLastColumn();
int firstRow = range.getFirstRow();
int lastRow = range.getLastRow();
if (row >= firstRow && row <= lastRow) {
if (column >= firstColumn && column <= lastColumn) {
return true;
}
}
}
return false;
}
/**
* 获取合并单元格的值
* @param sheet
* @param row 行下标
* @param column 列下标
* @return
*/
public String getMergedRegionValue(Sheet sheet, int row, int column) {
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress ca = sheet.getMergedRegion(i);
int firstColumn = ca.getFirstColumn();
int lastColumn = ca.getLastColumn();
int firstRow = ca.getFirstRow();
int lastRow = ca.getLastRow();
if (row >= firstRow && row <= lastRow) {
if (column >= firstColumn && column <= lastColumn) {
Row fRow = sheet.getRow(firstRow);
Cell fCell = fRow.getCell(firstColumn);
return getStringCellValue(fCell);
}
}
}
return "";
}
/**
* 获取excel的值 返回的 List<List<String>>的数据结构
* @param fileUrl 文件路径
* @param sheetNum 工作表(第几分页[1,2,3.....])
* @return List<List<String>>
*/
public List<List<String>> getExcelValues(String fileUrl, int sheetNum) throws Exception{
List<List<String>> values = new ArrayList<List<String>>();
File file = new File(fileUrl);
InputStream is = new FileInputStream(file);
Workbook workbook = WorkbookFactory.create(is);
int sheetCount = sheetNum-1; //workbook.getNumberOfSheets();//sheet 数量,可以只读取手动指定的sheet页
//int sheetCount1= workbook.getNumberOfSheets();
Sheet sheet = workbook.getSheetAt(sheetCount); //读取第几个工作表sheet
int rowNum = sheet.getLastRowNum();//有多少行
for (int i = 1; i <= rowNum; i++) {
Row row = sheet.getRow(i);//第i行
if (row == null) {//过滤空行
continue;
}
List<String> list = new ArrayList<>();
int colCount = sheet.getRow(0).getLastCellNum();//用表头去算有多少列,不然从下面的行计算列的话,空的就不算了
for (int j = 0; j < colCount; j++) {//第j列://+1是因为最后一列是空 也算进去
Cell cell = row.getCell(j);
String cellValue;
boolean isMerge = false;
if (cell != null) {
isMerge = isMergedRegion(sheet, i, cell.getColumnIndex());
}
//判断是否具有合并单元格
if (isMerge) {
cellValue = getMergedRegionValue(sheet, row.getRowNum(), cell.getColumnIndex());
} else {
cellValue = getStringCellValue(cell);
}
list.add(cellValue);
}
values.add(list);
}
return values;
}
/**
* 判断整行是否为空
* @param row excel得行对象
* @param maxRow 有效值得最大列数
*/
private static boolean CheckRowNull(Row row, int maxRow) {
int num = 0;
for (int j = 0; j < maxRow; j++) {
Cell cell=row.getCell(j);
if (cell==null||cell.equals("")||cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
num++;
}
}
if(maxRow==num) return true;
return false;
}
/**
* 根据sheet数获取excel的值 返回List<List<Map<String,String>>>的数据结构
* @param fileUrl 文件路径
* @param sheetNum 工作表(第几分页[1,2,3.....])
* @return List<List<Map<String,String>>>
*/
public List<List<Map<String,String>>> getExcelMapVal(String fileUrl, int sheetNum) throws Exception{
List<List<Map<String,String>>> values = new ArrayList<List<Map<String,String>>>();
File file = new File(fileUrl);
InputStream is = new FileInputStream(file);
Workbook workbook = WorkbookFactory.create(is);
int sheetCount = sheetNum - 1; //workbook.getNumberOfSheets();//sheet 数量,可以只读取手动指定的sheet页
//int sheetCount1= workbook.getNumberOfSheets();
Sheet sheet = workbook.getSheetAt(sheetCount); //读取第几个工作表sheet
int rowNum = sheet.getLastRowNum();//有多少行
Row rowTitle = sheet.getRow(0);//第i行
int colCount = sheet.getRow(0).getLastCellNum();//用表头去算有多少列,不然从下面的行计算列的话,空的就不算了
for (int i = 1; i <= rowNum; i++) {
Row row = sheet.getRow(i);//第i行
if (row == null || CheckRowNull(row,colCount)) {//过滤空行
continue;
}
List<Map<String,String>> list = new ArrayList<Map<String,String>>();
for (int j = 0; j < colCount; j++) {//第j列://+1是因为最后一列是空 也算进去
Map<String,String> map=new HashMap<>();
Cell cell = row.getCell(j);
Cell cellTitle = rowTitle.getCell(j);
String cellValue;
String cellKey=getStringCellValue(cellTitle);
boolean isMerge = false;
if (cell != null) {
isMerge = isMergedRegion(sheet, i, cell.getColumnIndex());
}
//判断是否具有合并单元格
if (isMerge) {
cellValue = getMergedRegionValue(sheet, row.getRowNum(), cell.getColumnIndex());
} else {
cellValue = getStringCellValue(cell);
}
map.put(cellKey,cellValue);
list.add(map);
}
values.add(list);
}
return values;
}
/**
* 获取当前excel的工作表sheet总数
* @param fileUrl
* @return
* @throws Exception
*/
public int hasSheetCount(String fileUrl)throws Exception{
File file = new File(fileUrl);
InputStream is = new FileInputStream(file);
Workbook workbook = WorkbookFactory.create(is);
int sheetCount= workbook.getNumberOfSheets();
return sheetCount;
}
public static class Column {
//单元格内容
private String content;
//字段名称,用户导出表格时反射调用
private String fieldName;
//这个单元格的集合
private List<Column> listTpamscolumn = new ArrayList<Column>();
int totalRow;
int totalCol;
int row;//excel第几行
int col;//excel第几列
int rLen; //excel 跨多少行
int cLen;//excel跨多少列
private boolean HasChilren;//是否有子节点
private int tree_step;//树的级别 从0开始
private String id;
private String pid;
public Column(){};
public Column(String content, String fieldName){
this.content = content;
this.fieldName = fieldName;
}
public Column(String fieldName, String content, int tree_step) {
this.tree_step = tree_step;
this.fieldName = fieldName;
this.content = content;
}
public int getTotalRow() {
return totalRow;
}
public void setTotalRow(int totalRow) {
this.totalRow = totalRow;
}
public int getTotalCol() {
return totalCol;
}
public void setTotalCol(int totalCol) {
this.totalCol = totalCol;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean isHasChilren() {
return HasChilren;
}
public void setHasChilren(boolean hasChilren) {
HasChilren = hasChilren;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public List<Column> getListTpamscolumn() {
return listTpamscolumn;
}
public void setListTpamscolumn(List<Column> listTpamscolumn) {
this.listTpamscolumn = listTpamscolumn;
}
public int getTree_step() {
return tree_step;
}
public void setTree_step(int tree_step) {
this.tree_step = tree_step;
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getCol() {
return col;
}
public void setCol(int col) {
this.col = col;
}
public int getrLen() {
return rLen;
}
public void setrLen(int rLen) {
this.rLen = rLen;
}
public int getcLen() {
return cLen;
}
public void setcLen(int cLen) {
this.cLen = cLen;
}
}
public static class TreeTool {
/**
* 传入的id 必须存在list集合里
* 获取某节点的深度
* @param list
* @param id 根节点
* @param step
* @return
*/
public static int getTreeStep(List<Column> list, String id, int step) {
if("".equals(id) || null == id) return step;
for (Column cc : list) {
if (id.equals(cc.getId())) {
int temp = step + 1;
return getTreeStep(list, cc.getPid(), temp);
}
}
return step;
}
/**
* 遍历所有数据 获取树最大的深度
* @param list
* @return
*/
public static int getMaxStep(List<Column> list){
List<Integer> nums=new ArrayList<Integer>();
for(Column cc:list){
nums.add( getTreeStep( list,cc.getId(),0));
}
return Collections.max(nums);
}
/**
* 获取最底部子节点的个数 所有叶子节点个数
* @param list
* @param did
* @return
*/
public static int getDownChilren(List<Column> list, String did){
int sum=0;
for(Column cc:list){
if(did.equals(cc.getPid())){
sum++;
//判断该节点 是否有子节点
if(hasChild(list,cc)) {
sum+= getDownChilren(list, cc.getId())-1;
}
}
}
return sum;
}
/**
* 获取父节点
* @param list 所有的list数据,一条一条
* @param did 当前节点id
* @return
*/
public static Column getFCol(List<Column> list, String did){
for(Column cc:list) {
if (did !=null && did.equals(cc.getId())) {
return cc;
}
if (did ==null && did == cc.getId()) {
return cc;
}
}
return new Column(){{setCol(0);setRow(0);}};
}
/**
* 获取兄弟节点个数 这个必须是有排序的
* @param list 所有的list数据,一条一条
* @param column 当前节点信息
* @return
*/
public static int getBrotherChilNum(List<Column> list, Column column ){
int sum=0;
for(Column cc:list){
if(column.getId().equals(cc.getId()))break;
if(!column.getPid().equals(cc.getPid()))continue;
int temp = getDownChilren(list, cc.getId());
if(temp == 0 || temp == 1)
sum++;
else
sum += temp;
}
return sum;
}
/**
* 根据某节点的第几层的父节点id
* @param list 所有的list数据,一条一条
* @param id 当前节点id
* @param step 第几层(深度 从零开始)
* @return
*/
public static String getStepFid(List<Column> list, String id, int step){
String f_id = null;
for (Column cc : list) {
if (id.equals(cc.getId())) {
int cstep = getTreeStep( list, cc.getId(), 0);
if(step == cstep){
return id;
}
int fstep = getTreeStep( list, cc.getPid(), 0);
if(step == fstep){
f_id = cc.getPid();break;
}else {
getStepFid( list, cc.getPid(), step);
}
}
}
return f_id;
}
/**
* 判断是否有子节点
* @param list 遍历的数据
* @param node 某个节点
* @return
*/
public static boolean hasChild(List<Column> list, Column node) {
return getChildList(list, node).size() > 0 ? true : false;
}
/**
* 得到子节点列表
* @param list 遍历的数据
* @param node 某个节点
* @return
*/
public static List<Column> getChildList(List<Column> list, Column node) {
List<Column> nodeList = new ArrayList<Column>();
Iterator<Column> it = list.iterator();
while (it.hasNext()) {
Column n = (Column) it.next();
if (n.getPid()!=null && n.getPid().equals( node.getId())) {
nodeList.add(n);
}
}
return nodeList;
}
/**
* 使用递归方法建树
* @param treeNodes
* @return
*/
public static List<Column> buildByRecursive(List<Column> treeNodes,String rootID) {
List<Column> trees = new ArrayList<>();
boolean flag = false;
boolean sflag = false;
for (Column treeNode : treeNodes) {
if ((rootID == null && rootID == treeNode.getId()) ) {
flag = true;
}
if( rootID != null && rootID.equals(treeNode.getId())){
flag = true;
}
if(flag) {
trees.add(findChildren(treeNode, treeNodes));
flag = false;
}
}
if(trees.size() <= 0) {
for (Column treeNode : treeNodes) {
if ((rootID == null && rootID == treeNode.getPid()) ) {
sflag = true;
}
if( rootID != null && rootID.equals(treeNode.getPid())){
sflag = true;
}
if(sflag){
trees.add(findChildren(treeNode,treeNodes));
sflag = false;
}
}
}
return trees;
}
/**
* 递归查找子节点
* @param treeNodes
* @return
*/
public static Column findChildren(Column treeNode, List<Column> treeNodes) {
for (Column it : treeNodes) {
if(treeNode.getId().equals(it.getPid())) {
if (treeNode.getListTpamscolumn() == null) {
treeNode.setListTpamscolumn(new ArrayList<Column>());
}
treeNode.getListTpamscolumn().add(findChildren(it,treeNodes));
}
}
return treeNode;
}
}
}
...@@ -9,6 +9,7 @@ import cn.ibizlab.core.extensions.dto.FetchParam; ...@@ -9,6 +9,7 @@ import cn.ibizlab.core.extensions.dto.FetchParam;
import cn.ibizlab.core.extensions.dto.FetchResult; import cn.ibizlab.core.extensions.dto.FetchResult;
import cn.ibizlab.core.extensions.service.BuildResultService; import cn.ibizlab.core.extensions.service.BuildResultService;
import cn.ibizlab.core.extensions.service.DACoreService; import cn.ibizlab.core.extensions.service.DACoreService;
import cn.ibizlab.util.errors.BadRequestAlertException;
import cn.ibizlab.util.helper.DataObject; import cn.ibizlab.util.helper.DataObject;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
...@@ -24,6 +25,8 @@ import org.springframework.http.ResponseEntity; ...@@ -24,6 +25,8 @@ import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.List; import java.util.List;
...@@ -42,16 +45,7 @@ public class DAGridCoreResource { ...@@ -42,16 +45,7 @@ public class DAGridCoreResource {
@Lazy @Lazy
private DictOptionServiceImpl dictOptionService; private DictOptionServiceImpl dictOptionService;
@Autowired
private BuildResultService buildResultService;
@RequestMapping(method = RequestMethod.GET, value = {"/dst/report/{reportId}/{dimValue}","/dst/report/{reportId}"})
public ResponseEntity<FetchResult> getReportdatas(@PathVariable(name = "reportId") String reportId, @PathVariable(name = "dimValue",required = false) String dimValue,
@RequestParam(name = "startTime",required = false) String startTime,
@RequestParam(name = "endTime",required = false) String endTime) {
FetchParam param=new FetchParam().setReportId(reportId).setDimValue(dimValue).setStartTime(DataObject.getTimestampValue(startTime,null)).setEndTime(DataObject.getTimestampValue(endTime,null));
return ResponseEntity.ok(buildResultService.getAnalyseResult(param));
}
@RequestMapping(method = RequestMethod.POST, value = "/ibizutil/reportdatas") @RequestMapping(method = RequestMethod.POST, value = "/ibizutil/reportdatas")
public ResponseEntity<JSONObject> getReportdatas(@RequestBody JSONObject data) { public ResponseEntity<JSONObject> getReportdatas(@RequestBody JSONObject data) {
......
package cn.ibizlab.api.rest.extensions; package cn.ibizlab.api.rest.extensions;
import cn.ibizlab.core.dict.extensions.service.DictDstService; import cn.ibizlab.core.dict.extensions.service.DictDstService;
import cn.ibizlab.core.extensions.dto.FetchParam;
import cn.ibizlab.core.extensions.dto.FetchResult;
import cn.ibizlab.core.extensions.service.BuildResultService;
import cn.ibizlab.core.lite.domain.DstSystem; import cn.ibizlab.core.lite.domain.DstSystem;
import cn.ibizlab.core.lite.domain.MetaEntity; import cn.ibizlab.core.lite.domain.MetaEntity;
import cn.ibizlab.core.lite.domain.MetaField; import cn.ibizlab.core.lite.domain.MetaField;
...@@ -16,12 +19,15 @@ import cn.ibizlab.core.lite.service.IMetaFieldService; ...@@ -16,12 +19,15 @@ import cn.ibizlab.core.lite.service.IMetaFieldService;
import cn.ibizlab.util.dict.CodeItem; import cn.ibizlab.util.dict.CodeItem;
import cn.ibizlab.util.dict.CodeList; import cn.ibizlab.util.dict.CodeList;
import cn.ibizlab.util.dict.Option; import cn.ibizlab.util.dict.Option;
import cn.ibizlab.util.errors.BadRequestAlertException;
import cn.ibizlab.util.filter.QueryFilter; import cn.ibizlab.util.filter.QueryFilter;
import cn.ibizlab.util.helper.DataObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
...@@ -29,6 +35,8 @@ import org.springframework.util.StringUtils; ...@@ -29,6 +35,8 @@ import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -279,4 +287,74 @@ public class DstCoreResource { ...@@ -279,4 +287,74 @@ public class DstCoreResource {
} }
@Autowired
private BuildResultService buildResultService;
@RequestMapping(method = RequestMethod.GET, value = {"/dst/report/{reportId}/{dimValue}/config","/dst/report/{reportId}/config",
"/lite/report/{reportId}/{dimValue}/config","/lite/report/{reportId}/config"})
public ResponseEntity<FetchResult> getReportViews(@PathVariable(name = "reportId") String reportId, @PathVariable(name = "dimValue",required = false) String dimValue,
@RequestParam(name = "startTime",required = false) String startTime,
@RequestParam(name = "endTime",required = false) String endTime) {
FetchParam param=new FetchParam().setReportId(reportId).setDimValue(dimValue).setStartTime(DataObject.getTimestampValue(startTime,null)).setEndTime(DataObject.getTimestampValue(endTime,null));
return ResponseEntity.ok(buildResultService.getReportConfig(param));
}
@RequestMapping(method = RequestMethod.GET, value = {"/dst/report/{reportId}/{dimValue}","/dst/report/{reportId}",
"/lite/report/{reportId}/{dimValue}","/lite/report/{reportId}"})
public ResponseEntity<FetchResult> getReportdatas(@PathVariable(name = "reportId") String reportId, @PathVariable(name = "dimValue",required = false) String dimValue,
@RequestParam(name = "startTime",required = false) String startTime,
@RequestParam(name = "endTime",required = false) String endTime) {
FetchParam param=new FetchParam().setReportId(reportId).setDimValue(dimValue).setStartTime(DataObject.getTimestampValue(startTime,null)).setEndTime(DataObject.getTimestampValue(endTime,null));
return ResponseEntity.ok(buildResultService.getAnalyseResult(param));
}
@RequestMapping(method = RequestMethod.GET, value = {"/dst/report/{reportId}/{dimValue}.xls","/dst/report/{reportId}.xls",
"/lite/report/{reportId}/{dimValue}.xls","/lite/report/{reportId}.xls"})
public void exportReportdatas(@PathVariable(name = "reportId") String reportId, @PathVariable(name = "dimValue",required = false) String dimValue,
@RequestParam(name = "startTime",required = false) String startTime,
@RequestParam(name = "endTime",required = false) String endTime, HttpServletResponse response) {
FetchParam param=new FetchParam().setReportId(reportId).setDimValue(dimValue).setStartTime(DataObject.getTimestampValue(startTime,null)).setEndTime(DataObject.getTimestampValue(endTime,null));
File file = buildResultService.exportExcel(param);
if(file==null)
throw new BadRequestAlertException("导出报表失败","Report",reportId);
try {
response.setHeader("Content-Disposition", "attachment;filename="+new String(file.getName().getBytes("utf-8"),"iso8859-1"));//防止中文乱码
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
}
catch (Exception e) {
//throw e;
}
finally {
if (bis != null) {
try {
bis.close();
}
catch (IOException e) {
}
}
if (bos != null) {
try {
bos.close();
}
catch (IOException e) {
}
}
}
}
} }
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册