[WebApi]歷史資料新增CSV功能

This commit is contained in:
張家睿 2024-07-23 11:54:14 +08:00
parent 812ee2ffc0
commit 85b5c468db

View File

@ -311,6 +311,68 @@ namespace FrontendWebApi.ApiControllers
return File(ms, "application/vnd.ms-excel", fileName);
}
[HttpPost]
[Route("api/ExportCSV")]
public async Task<IActionResult> ExportCSV(PostHistoryRawDataFilter input)
{
ApiResult<string> apiResult = new ApiResult<string>();
try
{
var apiData = await GetHistoryRealTime(input);
if (apiData.Value == null)
{
var msg = new { Code = "0003", Msg = "無資料可匯出。" };
return StatusCode(400, msg);
}
var rawData = apiData.Value.Data;
var FileName = $"歷史資料_{DateTime.Now}.csv";
// 生成CSV文件
string Csv = null;
if (rawData.Count > 0)
{
StringBuilder csv = new StringBuilder();
// 添加CSV標題行
csv.AppendLine("區域,系統大類,系統小類,設備編號,設備名稱,設備項目,數值,紀錄時間");
// 添加數據行
foreach (var item in rawData)
{
csv.AppendLine($"{item.Building_name},{item.Main_system_name},{item.Sub_system_name},{item.Device_number},{item.Item_name},{item.Points},{item.Value},{item.Timestamp}");
}
Csv = csv.ToString();
}
// 返回CSV文件
if (Csv != null)
{
using (var electricMemoryStream = new MemoryStream())
{
using (var streamWriter = new StreamWriter(electricMemoryStream, Encoding.UTF8))
{
streamWriter.Write(Csv);
}
return File(electricMemoryStream.ToArray(), "text/csv", FileName);
}
}
else
{
var msg = new { Code = "0003", Msg = "無資料可匯出。" };
return StatusCode(400, msg);
}
}
catch (Exception exception)
{
apiResult.Code = "9999";
apiResult.Msg = "系統內部錯誤,請聯絡管理者。 Msg: " + exception.Message;
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Json(apiResult);
}
}
/// <summary>
/// 即時趨勢條件過濾條件面板
/// </summary>
@ -395,7 +457,7 @@ namespace FrontendWebApi.ApiControllers
}
}
var devices = dbsub.Where(x => x.main_system_tag == main.Select(m => m.main_system_tag).FirstOrDefault() && x.sub_system_tag == sub.Select(x => x.sub_system_tag).FirstOrDefault() && x.device_number != null).OrderBy(x=>x.device_full_name.Length).ThenBy(x=>x.device_full_name).ToList();
var devices = dbsub.Where(x => x.main_system_tag == main.Select(m => m.main_system_tag).FirstOrDefault() && x.sub_system_tag == sub.Select(x => x.sub_system_tag).FirstOrDefault() && x.device_number != null).OrderBy(x => x.device_full_name.Length).ThenBy(x => x.device_full_name).ToList();
history_Sub_System.device = devices.Count > 0 ? new List<Device>() : null;
foreach (var d in devices)
{
@ -406,18 +468,18 @@ namespace FrontendWebApi.ApiControllers
history_Sub_System.device.Add(device);
}
if (history_Sub_System.is_show_history==1)
if (history_Sub_System.is_show_history == 1)
{
history_Main_System.History_Sub_systems.Add(history_Sub_System);
}
}
apiResult.Data.history_Main_Systems.Add(history_Main_System);
apiResult.Data.history_Main_Systems.Add(history_Main_System);
}
apiResult.Data.history_Builds = dbbuilding;
apiResult.Code = "0000";
}
catch (Exception exception)
@ -1091,7 +1153,7 @@ namespace FrontendWebApi.ApiControllers
}
/// <summary>
/// 取得歷史資料
/// 取得歷史資料(從Niagara拿資料)
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
@ -1319,26 +1381,27 @@ namespace FrontendWebApi.ApiControllers
}
/// <summary>
/// 即使歷史資料(前7天)
/// 即時歷史資料(從MSSQL拿資料)
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost]
[Route("api/HistoryRealTime")]
public async Task<ActionResult<ApiResult<List<HistoryRawData>>>> GetHistoryRealTime (PostHistoryRawDataFilter input)
public async Task<ActionResult<ApiResult<List<HistoryRawData>>>> GetHistoryRealTime(PostHistoryRawDataFilter input)
{
ApiResult<List<HistoryRawData>> apiResult = new ApiResult<List<HistoryRawData>>(jwt_str);
apiResult.Data = new List<HistoryRawData>();
List<string> noDataDevice = new List<string>();
if (!jwtlife)
{
apiResult.Code = "5000";
return BadRequest(apiResult);
return apiResult;
}
if (input.HistoryItems.Count == 0)
if (input.HistoryItems == null)
{
apiResult.Code = "9998";
apiResult.Msg = "沒有設備被選擇";
return BadRequest(apiResult);
return apiResult;
}
try
@ -1387,7 +1450,7 @@ namespace FrontendWebApi.ApiControllers
var sql = $@"select '{device_item_info.Building_name}' as Building_name, '{device_item_info.Main_system_name}' as Main_system_name,
'{device_item_info.Sub_system_name}' as Sub_system_name, '{device_item_info.Device_number}' as Device_number,
'{device_item_info.Device_name}' as Device_name, '{device_item_info.Item_name}' as Item_name, '{device_item_info.Points}' as Points,
'{device_item_info.Unit}' as Unit, timestamp as Timestamp,
'{device_item_info.Unit}' as Unit, FORMAT(timestamp, 'yyyy-MM-dd HH:mm:ss') as Timestamp,
{(valueType.Equals("bit") ? "Case when value = 1 then 'true' when value = 0 then 'false' else 'Unknow' End" : "round(value, 2)")} as Value
from {tableName}
where replace(convert(varchar, [timestamp], 111), '/', '-') >= @startTime
@ -1396,21 +1459,23 @@ namespace FrontendWebApi.ApiControllers
await backgroundServiceMsSqlRepository.GetAllAsync<HistoryRawData>(sql, new { startTime = input.Start_timestamp, endTime = input.End_timestamp })
);
}
//foreach (var tn in tableName)
//{
//}
else
{
noDataDevice.Add(hi.Device_number_point);
}
}
apiResult.Code = "0000";
apiResult.Data = apiResult.Data.OrderBy(x => x.Device_number).ThenBy(x => x.Timestamp).ToList();
apiResult.Msg = @$"DB無資料的設備{string.Join(".", noDataDevice)}";
apiResult.Data = apiResult.Data.OrderBy(x => x.Device_number).ThenByDescending(x => x.Timestamp).ToList();
}
catch (Exception exception)
{
apiResult.Code = "9999";
apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Ok(apiResult);
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message + exception.StackTrace);
return apiResult;
}
return Ok(apiResult);
return apiResult;
}
private List<Dictionary<string, object>> ArrangeRawData(DeviceNumberPoint deviceNumberPoint, JObject jsonResult)