1. 程式人生 > >檢索資料匯出Excel

檢索資料匯出Excel

        在前端進行資料檢索時,通常會將根據條件檢索到某個資料的列表排序,而這種資訊對於使用者來說有的時候會很不方便,因此需要將查詢結果匯出到excel檔案中,方便使用者進行檢視對比;

步驟一:呼叫GetQueryIdByCondition獲取到QueryId

功能 根據查詢引數獲取QueryId
介面 HTTP://IP:PORT/api/biz/export/quertid/{QueryType}
呼叫方式 HTTP POST
資料型別 JSON
輸入 {
    "BaseQuery":{
        "Limit":10,
        "Offset":0,
        "id":[
        ],
"QueryId":"warnall__Ro3lTvA3epetAcxAkfSM1hrqOhjv1bbO",
        "QueryTimeSpacialRanges":[
            {
                "SpacialRange":[
                ],
                "TimeRange":{
                }
            }
        ]
    },
    "RuleName":""
}
輸出 {
  "Code": 1,
  "Msg": "success",
  "Redirect": "",
  "Data": {
    "QueryId": "export:allalarm:{uuid}”
  }
}
說明 (1)QueryType為不同的匯出介面對應的查詢的type標識(2)輸入例子以匯出報警為例(3)部分匯出時:需要指定具體的記錄的id,Id為uuid的字串,忽略其他前端傳入的檢索條件,在資料庫中檢索時只是根據傳入記錄的唯一id進行檢索(4)全部匯出的時候相當於先走檢索條件,再將符合檢索條件的記錄全部匯出

流程說明:

1、先獲取URL中傳入的QueryType,得到QueryType的型別判斷要匯出的資訊;

2、得到要匯出的資訊,判斷body中傳入的引數是否符合要匯出資訊的查詢條件;

3、建立要匯出的物件(例如:new(models.MonitorAlarmCivilQuery)),將前端傳入的查詢條件繫結到建立的物件判斷是否出錯,出錯則為前端傳入引數有誤;否則得到符合查詢條件的資料,然後將查詢條件查詢到的資料存入到Redis快取中;

4、將快取的資訊以QueryId:export:allalarm:{uuid}的資訊返回。

步驟二:呼叫對應的匯出介面

功能 匯出需要匯出的資訊
介面 HTTP://IP:PORT/api/biz/civilalarm/export?QueryId=export:civilalarm:{uuid}
呼叫方式 HTTP GET
資料型別 JSON
輸入 QueryId
輸出 具體匯出的檔案的壓縮包

流程說明:

1、首先獲取前端傳入的QueryId,如果為空則返回引數錯誤;否則呼叫strings.Contains(queryId, “export:allalarm”)判斷傳入引數中是否包含指定的字串資訊;

2、不包括則為引數錯誤返回;否則呼叫GetQueryConditionById方法去獲取Redis快取中的資料,返回快取的查詢條件;

3、判斷查詢條件是否為空為空則返回引數錯誤;否則根據拿到的引數去判斷查詢中是否傳入了具體記錄的id,如果記錄id存在則呼叫通過id取資料庫中查詢的方法;否則說明為全部匯出,根據傳入的查詢條件去資料庫中獲取資料;

4、如果獲取到了資料呼叫相應的建立Excel的方法,將查詢的資料寫入到Excel表格並對匯出的檔案進行相應的壓縮處理和檔名處理。

步驟三:主要程式碼實現:

//呼叫GetQueryIdByCondition通過QueryId獲取查詢Id,進行Redis快取
func (this *CommonController) GetQueryIdByCondition(c *gin.Context) {
	var queryType = c.Query("QueryType")

	searchResp := new(models.SearchResp)
	var query interface{}
	var retMap = make(map[string]string, 0)

	if queryType == "1" {
		query, searchResp = this.validVehicleRequest(c)
	} else if queryType == "2" {
		query, searchResp = this.validPedestrianRequest(c)
	} else if queryType == "3" {
		query, searchResp = this.validMotorVehicleQuery(c)
	} else if queryType == "4" {
		query, searchResp = this.validFaceRequest(c)
	} else if queryType == "5" {
		query, searchResp = this.validBaseQuery(c)
	} else if queryType == "6" {
		query, searchResp = this.validAllMonitorAlarmQueryRequest(c)
	} else if queryType == "7" {
		query, searchResp = this.validCivilMonitorAlarmQueryRequest(c)
	} else if queryType == "8" {
		query, searchResp = this.validVehicleMonitorAlarmQueryRequest(c)
	}

	if query == nil {
		searchResp.Code = models.ApiStatus_ERROR
		c.JSON(http.StatusBadRequest, searchResp)
	} else {
		retMap["QueryId"] = this.CacheQueryCondition(query)
		searchResp.Data = retMap
		c.JSON(http.StatusOK, searchResp)
	}

}
//以validAllMonitorAlarmQueryRequest為例
func (this *CommonController) validAllMonitorAlarmQueryRequest(c *gin.Context) (*models.MonitorAlarmAllQuery, *models.SearchResp) {
	monitorAlarmQuery := new(models.MonitorAlarmAllQuery)
	searchResp := &models.SearchResp{
		Code: models.ApiStatus_SUCCESS,
		Msg:  "success",
	}
	var queryId = c.Query("QueryId")
	if queryId != "" {
		if strings.Contains(queryId, "export:allalarm") {
			var query = this.GetQueryConditionById(queryId)
			if nil != query {
				monitorAlarmQuery = query.(*models.MonitorAlarmAllQuery)
			}
		}
	}else {
		if err := c.BindJSON(monitorAlarmQuery); err != nil {
			glog.Errorln(err)
			return nil, MONITOR_ALARM_FORMAT_PARAM_ERROR
		}
	}
	if monitorAlarmQuery.BaseQuery == nil {
		return nil, MONITOR_ALARM_FORMAT_PARAM_ERROR
	}

	glog.V(1).Infoln(monitorAlarmQuery)

	return monitorAlarmQuery, searchResp

}
//具體快取前端的查詢條件
func (this *CommonController) CacheQueryCondition(query interface{}) string {

	var t = ""
	switch query.(type) {
	case *models.VehicleQuery:
		t = "vec"
	case *models.PedestrianQuery:
		t = "ped"
	case *models.MotorVehicleQuery:
		t = "nmotor"
	case *models.FaceQuery:
		t = "face"
	case *models.BaseQuery:
		t = "base"
	case *models.MonitorAlarmAllQuery:
		t = "allalarm"
	case *models.MonitorAlarmCivilQuery:
		t = "civilalarm"
	case *models.MonitorAlarmVehicleQuery:
		t = "vehiclealarm"
	}

	var key = ""
	if t != "" {
		key = fmt.Sprintf("export:%s:%s", t, utils.NewV4().String())

		body, _ := json.Marshal(query)
		utils.RedisClient.Set(key, body, 60*30)
	}

	return key

}

//通過查詢條件獲取QueryId
func (this *CommonController) GetQueryConditionById(queryId string) interface{} {
	if utils.RedisClient.Exists(queryId) {
		cache, err := utils.RedisClient.GetRaw(queryId)
		if nil == err {
			if strings.Contains(queryId, "vec") {
				var query = new(models.VehicleQuery)
				json.Unmarshal(cache, query)
				return query
			} else if strings.Contains(queryId, "ped") {
				var query = new(models.PedestrianQuery)
				json.Unmarshal(cache, query)
				return query
			} else if strings.Contains(queryId, "nmotor") {
				var query = new(models.MotorVehicleQuery)
				json.Unmarshal(cache, query)
				return query
			} else if strings.Contains(queryId, "face") {
				var query = new(models.FaceQuery)
				json.Unmarshal(cache, query)
				return query
			} else if strings.Contains(queryId, "base") {
				var query = new(models.BaseQuery)
				json.Unmarshal(cache, query)
				return query
			} else if strings.Contains(queryId, "allalarm") {
				var query = new(models.MonitorAlarmAllQuery)
				json.Unmarshal(cache, query)
				return query
			} else if strings.Contains(queryId, "civilalarm") {
				var query = new(models.MonitorAlarmCivilQuery)
				json.Unmarshal(cache, query)
				return query
			} else if strings.Contains(queryId, "vehiclealarm") {
				var query = new(models.MonitorAlarmVehicleQuery)
				json.Unmarshal(cache, query)
				return query
			}
		}

	}
	return nil

}

//具體的匯出介面
// 全部報警匯出介面
func (this *CommonController) ExportMonitorAlarmAll(c *gin.Context) {
	monitorAlarmQuery, searchResp := this.validAllMonitorAlarmQueryRequest(c)
	if monitorAlarmQuery == nil {
		c.JSON(http.StatusBadRequest, searchResp)
		return
	}
	//匯出最多條數
	if monitorAlarmQuery.GetBaseQuery().Limit > exportstream.EXPORT_MAX_ROWS {
		monitorAlarmQuery.GetBaseQuery().Limit = exportstream.EXPORT_MAX_ROWS
	}

	var userId = ""
	if uid, ok := c.Get(db_model.SESSION_USER_ID); ok {
		userId = uid.(string)
	}

	var uniqueAlarmIds = "{}"
	if nil != monitorAlarmQuery.GetBaseQuery() {
		if len(monitorAlarmQuery.GetBaseQuery().Id) > 0 {
			uniqueAlarmIds = utils.GetArrayAnySqlStr(monitorAlarmQuery.GetBaseQuery().Id)
		}
	}

	var alarmBaseQuery = monitorAlarmQuery.BaseQuery
	var monitorAlarmList = make([]*models.MonitorAlarmView, 0)
	var count int32
	if len(alarmBaseQuery.Id) > 0 {
		monitorAlarmList, count = this.Service.ListMonitorAlarmAll(uniqueAlarmIds, "", "", 0, 0, alarmBaseQuery.SortOrderAsc, 0, 10)
	}else {
		sensorIdsStr, timeStart, timeEnd := this.getTimeSpacialConditionByQuery(userId, alarmBaseQuery)
		monitorAlarmList, count = this.Service.ListMonitorAlarmAll("", sensorIdsStr, monitorAlarmQuery.RuleName, timeStart, timeEnd, alarmBaseQuery.SortOrderAsc, 0, alarmBaseQuery.Limit)
	}
	if count > 0 {
		monitorAlarmExport := excelstream.NewExcelMonitorAlarmAllExport(monitorAlarmList)
		exportProcessor := &exportstream.ExportProcessor{monitorAlarmExport, &sync.Mutex{}}
		exportProcessor.ProcessExport(c)
	}
}