[WebApi]歷史資料匯出改成一頁式,並修正排序問題

This commit is contained in:
張家睿 2024-06-05 17:31:48 +08:00
parent 84fd45c601
commit b652aa1533

View File

@ -63,8 +63,8 @@ namespace FrontendWebApi.ApiControllers
: lhe.dateType == "month" ? lhe.starttime.ToString("yyyy-MM") : lhe.dateType == "month" ? lhe.starttime.ToString("yyyy-MM")
: lhe.starttime.ToString("yyyy-MM-dd") + "_" + ((DateTime)lhe.endtime).ToString("yyyy-MM-dd"); : lhe.starttime.ToString("yyyy-MM-dd") + "_" + ((DateTime)lhe.endtime).ToString("yyyy-MM-dd");
string fileName = "歷史資料_" + fileDateName + ".xlsx"; string fileName = "歷史資料_" + fileDateName + ".xlsx";
lhe.device_number = char.IsDigit(lhe.device_number.Split("_")[1][0]) lhe.device_number = char.IsDigit(lhe.device_number.Split("_")[1][0])
? lhe.device_number.Replace(lhe.device_number.Split("_")[1], "$3" + lhe.device_number.Split("_")[1]) ? lhe.device_number.Replace(lhe.device_number.Split("_")[1], "$3" + lhe.device_number.Split("_")[1])
: lhe.device_number; : lhe.device_number;
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
try try
@ -179,7 +179,7 @@ namespace FrontendWebApi.ApiControllers
//hed.value = ard["@avg_rawdata"].ToString() == "-1" ? "NaN" : Math.Round((decimal.Parse(ard["@avg_rawdata"].ToString(), System.Globalization.NumberStyles.Float)), 2).ToString(); //hed.value = ard["@avg_rawdata"].ToString() == "-1" ? "NaN" : Math.Round((decimal.Parse(ard["@avg_rawdata"].ToString(), System.Globalization.NumberStyles.Float)), 2).ToString();
// 四捨五入 // 四捨五入
//ref: Math.Round(Convert.ToDecimal(45.365), 2, MidpointRounding.AwayFromZero) //ref: Math.Round(Convert.ToDecimal(45.365), 2, MidpointRounding.AwayFromZero)
hed.value = ard["@avg_rawdata"].ToString() == "-1" ? "NaN" : Math.Round(Convert.ToDecimal(ard["@avg_rawdata"].ToString()), 2, MidpointRounding.AwayFromZero).ToString(); hed.value = ard["@avg_rawdata"].ToString() == "-1" ? "NaN" : Math.Round(Convert.ToDecimal(ard["@avg_rawdata"].ToString()), 2, MidpointRounding.AwayFromZero).ToString();
hed.timestamp = Convert.ToDateTime(ard["@start_timestamp"].ToString()); hed.timestamp = Convert.ToDateTime(ard["@start_timestamp"].ToString());
hed.building_tag = d.building_tag; hed.building_tag = d.building_tag;
he.Add(hed); he.Add(hed);
@ -290,10 +290,11 @@ namespace FrontendWebApi.ApiControllers
#endregion #endregion
RowPosition = 1; RowPosition = 1;
} }
else { else
{
RowPosition += 1; RowPosition += 1;
} }
row = sheet.CreateRow(RowPosition); row = sheet.CreateRow(RowPosition);
for (var i = 0; i < 4; i++) for (var i = 0; i < 4; i++)
{ {
@ -375,9 +376,26 @@ namespace FrontendWebApi.ApiControllers
List<HistoryExport> he = new List<HistoryExport>(); List<HistoryExport> he = new List<HistoryExport>();
List<JsonDevice> jd = new List<JsonDevice>(); List<JsonDevice> jd = new List<JsonDevice>();
#region combine device and point #region combine device and point
// 因傳進來point不是比照前端順序故這邊又排序了一次
var Sql = $@"select c.full_name building_name,b.device_number,b.full_name device_name,a.full_name item_name,a.points,a.unit
from device_item a
join device b on a.device_system_tag = b.device_system_tag
and a.device_building_tag COLLATE utf8mb4_unicode_ci = b.device_building_tag
and a.device_name_tag COLLATE utf8mb4_unicode_ci = b.device_name_tag
join building c on c.building_tag = b.device_building_tag
join variable v1 on v1.system_value = b.device_system_tag and v1.deleted = 0 and v1.system_type = 'device_system_category_layer2'
join variable v2 on v2.system_value = b.device_name_tag and v2.deleted = 0 and v2.system_type = 'device_system_category_layer3'
where a.deleted = 0 and b.deleted = 0 and b.is_link = 1 and v2.deleted = 0 and v1.deleted = 0 and is_show_history = 1 and a.is_link = 1
and b.device_number = 'NTPC_G6_EE_E4_B1F_EMP_WHT_N1'
GROUP BY points
order by c.priority,b.priority,a.is_bool;";
var pointData = backendRepository.GetAllAsync<History_PostItem>(Sql).Result;
List<string> points = pointData.Select(x => x.points).ToList();
List<string> inputParams = post.Points;
inputParams.Sort((a, b) => points.IndexOf(a).CompareTo(points.IndexOf(b)));
foreach (var Device in post.Device_list) foreach (var Device in post.Device_list)
{ {
foreach (var point in post.Points) foreach (var point in inputParams)
{ {
DeviceNumberPoint deviceNumberPoint = new DeviceNumberPoint(); DeviceNumberPoint deviceNumberPoint = new DeviceNumberPoint();
deviceNumberPoint.DeviceNumber = Device; deviceNumberPoint.DeviceNumber = Device;
@ -396,7 +414,7 @@ namespace FrontendWebApi.ApiControllers
//轉換日期格式 //轉換日期格式
var start = string.Format("{0}T{1}:00.000+08:00", post.Start_date, post.Start_time); var start = string.Format("{0}T{1}:00.000+08:00", post.Start_date, post.Start_time);
var end = string.Format("{0}T{1}:01.000+08:00", post.End_date, post.End_time); var end = string.Format("{0}T{1}:10.000+08:00", post.End_date, post.End_time);
var historyQueryFilter = $@"<obj is='obix: HistoryFilter'> var historyQueryFilter = $@"<obj is='obix: HistoryFilter'>
<abstime name = 'start' val = '{start}' /> <abstime name = 'start' val = '{start}' />
@ -534,7 +552,7 @@ namespace FrontendWebApi.ApiControllers
{ {
//轉換日期格式 //轉換日期格式
var start = string.Format("{0}T{1}:00.000+08:00", day.ToString("yyyy-MM-dd"), post.Start_time); var start = string.Format("{0}T{1}:00.000+08:00", day.ToString("yyyy-MM-dd"), post.Start_time);
var end = string.Format("{0}T{1}:01.000+08:00", day.ToString("yyyy-MM-dd"), post.End_time); var end = string.Format("{0}T{1}:10.000+08:00", day.ToString("yyyy-MM-dd"), post.End_time);
var historyQueryFilter = $@"<obj is='obix: HistoryFilter'> var historyQueryFilter = $@"<obj is='obix: HistoryFilter'>
<abstime name = 'start' val = '{start}' /> <abstime name = 'start' val = '{start}' />
@ -628,7 +646,7 @@ namespace FrontendWebApi.ApiControllers
string buildingTag = d.DeviceNumber.Split("_")[1]; string buildingTag = d.DeviceNumber.Split("_")[1];
//取得時間 //取得時間
var abstime = obj["abstime"]["@val"].ToString(); var abstime = obj["abstime"]["@val"].ToString();
var val = obj["real"] != null ? var val = obj["real"] != null ?
obj["real"]["@val"].ToString() : obj["bool"]["@val"].ToString(); obj["real"]["@val"].ToString() : obj["bool"]["@val"].ToString();
HistoryExport hed = new HistoryExport(); HistoryExport hed = new HistoryExport();
@ -709,7 +727,10 @@ namespace FrontendWebApi.ApiControllers
stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.WrapText = true; stylein12.WrapText = true;
#endregion #endregion
var data = he.OrderByDescending(x => x.deviceName).ThenBy(x => x.type).ToList(); var data = he.GroupBy(x => new { x.deviceName, x.type })
.SelectMany(g => g.OrderByDescending(x => x.timestamp))
.ToList(); ;
if (data.Count > 0) if (data.Count > 0)
{ {
string lastDeviceItem = string.Empty; string lastDeviceItem = string.Empty;
@ -718,73 +739,79 @@ namespace FrontendWebApi.ApiControllers
IRow row; IRow row;
ISheet sheet; ISheet sheet;
#region set cell #region set cell
sheet = workbook.CreateSheet($"{building.Where(x => x.building_tag == data[0].device_number.Split("_")[1]).Select(x => x.full_name).FirstOrDefault()}{"_" + data[0].deviceName + "_" + data[0].type}"); //sheet = workbook.CreateSheet($"{building.Where(x => x.building_tag == data[0].device_number.Split("_")[1]).Select(x => x.full_name).FirstOrDefault()}{"_" + data[0].deviceName + "_" + data[0].type}");
sheet = workbook.CreateSheet($"歷史資料");
row = sheet.CreateRow(RowPosition); row = sheet.CreateRow(RowPosition);
sheet.SetColumnWidth(0, 4 * 160 * 12); sheet.SetColumnWidth(0, 4 * 160 * 12);
sheet.SetColumnWidth(1, 4 * 160 * 12); sheet.SetColumnWidth(1, 4 * 160 * 12);
sheet.SetColumnWidth(2, 4 * 160 * 12); sheet.SetColumnWidth(2, 4 * 160 * 12);
sheet.SetColumnWidth(3, 4 * 160 * 12); sheet.SetColumnWidth(3, 4 * 160 * 12);
sheet.SetColumnWidth(4, 4 * 160 * 12);
ICell cell = row.CreateCell(0); ICell cell = row.CreateCell(0);
cell.SetCellValue("類型"); cell.SetCellValue("棟別");
cell.CellStyle = styleLine12; cell.CellStyle = styleLine12;
cell = row.CreateCell(1); cell = row.CreateCell(1);
cell.SetCellValue("設備名稱"); cell.SetCellValue("設備名稱");
cell.CellStyle = styleLine12; cell.CellStyle = styleLine12;
cell = row.CreateCell(2); cell = row.CreateCell(2);
cell.SetCellValue("數值"); cell.SetCellValue("類型");
cell.CellStyle = styleLine12; cell.CellStyle = styleLine12;
cell = row.CreateCell(3); cell = row.CreateCell(3);
cell.SetCellValue("數值");
cell.CellStyle = styleLine12;
cell = row.CreateCell(4);
cell.SetCellValue("記錄時間"); cell.SetCellValue("記錄時間");
cell.CellStyle = styleLine12; cell.CellStyle = styleLine12;
#endregion #endregion
foreach (var d in data) foreach (var d in data)
{ {
if (RowPosition == 0 && lastDeviceItem == "" && lastDevice == "") //if (RowPosition == 0 && lastDeviceItem == "" && lastDevice == "")
{ //{
lastDeviceItem = d.type; //第一次不用建立 sheet; // lastDeviceItem = d.type; //第一次不用建立 sheet;
lastDevice = d.deviceName; // lastDevice = d.deviceName;
} //}
if (d.type != lastDeviceItem || d.deviceName != lastDevice) //if (d.type != lastDeviceItem || d.deviceName != lastDevice)
{ //{
RowPosition = 0; // RowPosition = 0;
lastDeviceItem = d.type; // lastDeviceItem = d.type;
lastDevice = d.deviceName; // lastDevice = d.deviceName;
sheet = workbook.CreateSheet($"{building.Where(x => x.building_tag == d.device_number.Split("_")[1]).Select(x => x.full_name).FirstOrDefault()}{"_" + d.deviceName + "_" + d.type}"); // sheet = workbook.CreateSheet($"{building.Where(x => x.building_tag == d.device_number.Split("_")[1]).Select(x => x.full_name).FirstOrDefault()}{"_" + d.deviceName + "_" + d.type}");
//sheet = workbook.CreateSheet($"{d.deviceName}{"_" + d.type}"); // //sheet = workbook.CreateSheet($"{d.deviceName}{"_" + d.type}");
#region set cell // #region set cell
row = sheet.CreateRow(RowPosition); // row = sheet.CreateRow(RowPosition);
sheet.SetColumnWidth(0, 4 * 160 * 12); // sheet.SetColumnWidth(0, 4 * 160 * 12);
sheet.SetColumnWidth(1, 4 * 160 * 12); // sheet.SetColumnWidth(1, 4 * 160 * 12);
sheet.SetColumnWidth(2, 4 * 160 * 12); // sheet.SetColumnWidth(2, 4 * 160 * 12);
sheet.SetColumnWidth(3, 4 * 160 * 12); // sheet.SetColumnWidth(3, 4 * 160 * 12);
cell = row.CreateCell(0); // cell = row.CreateCell(0);
cell.SetCellValue("類型"); // cell.SetCellValue("類型");
cell.CellStyle = styleLine12; // cell.CellStyle = styleLine12;
cell = row.CreateCell(1); // cell = row.CreateCell(1);
cell.SetCellValue("設備名稱"); // cell.SetCellValue("設備名稱");
cell.CellStyle = styleLine12; // cell.CellStyle = styleLine12;
cell = row.CreateCell(2); // cell = row.CreateCell(2);
cell.SetCellValue("數值"); // cell.SetCellValue("數值");
cell.CellStyle = styleLine12; // cell.CellStyle = styleLine12;
cell = row.CreateCell(3); // cell = row.CreateCell(3);
cell.SetCellValue("記錄時間"); // cell.SetCellValue("記錄時間");
cell.CellStyle = styleLine12; // cell.CellStyle = styleLine12;
#endregion // #endregion
RowPosition = 1; // RowPosition = 1;
} //}
else //else
{ //{
RowPosition += 1; // RowPosition += 1;
} //}
RowPosition += 1;
row = sheet.CreateRow(RowPosition); row = sheet.CreateRow(RowPosition);
for (var i = 0; i < 4; i++) for (var i = 0; i < 5; i++)
{ {
cell = row.CreateCell(i); cell = row.CreateCell(i);
if (i == 0) if (i == 0)
{ {
cell.SetCellValue(d.type); cell.SetCellValue(building.Where(x => x.building_tag == d.device_number.Split("_")[1]).Select(x => x.full_name).FirstOrDefault());
} }
if (i == 1) if (i == 1)
{ {
@ -792,9 +819,13 @@ namespace FrontendWebApi.ApiControllers
} }
if (i == 2) if (i == 2)
{ {
cell.SetCellValue(d.value); cell.SetCellValue(d.type);
} }
if (i == 3) if (i == 3)
{
cell.SetCellValue(d.value);
}
if (i == 4)
{ {
cell.SetCellValue(d.timestamp.ToString("yyyy-MM-dd HH:mm:ss")); cell.SetCellValue(d.timestamp.ToString("yyyy-MM-dd HH:mm:ss"));
} }
@ -1216,9 +1247,26 @@ namespace FrontendWebApi.ApiControllers
int pageSize = 10; int pageSize = 10;
int totalItems = 0; int totalItems = 0;
#region combine device and point #region combine device and point
// 因傳進來point不是比照前端順序故這邊又排序了一次
var Sql = $@"select c.full_name building_name,b.device_number,b.full_name device_name,a.full_name item_name,a.points,a.unit
from device_item a
join device b on a.device_system_tag = b.device_system_tag
and a.device_building_tag COLLATE utf8mb4_unicode_ci = b.device_building_tag
and a.device_name_tag COLLATE utf8mb4_unicode_ci = b.device_name_tag
join building c on c.building_tag = b.device_building_tag
join variable v1 on v1.system_value = b.device_system_tag and v1.deleted = 0 and v1.system_type = 'device_system_category_layer2'
join variable v2 on v2.system_value = b.device_name_tag and v2.deleted = 0 and v2.system_type = 'device_system_category_layer3'
where a.deleted = 0 and b.deleted = 0 and b.is_link = 1 and v2.deleted = 0 and v1.deleted = 0 and is_show_history = 1 and a.is_link = 1
and b.device_number = 'NTPC_G6_EE_E4_B1F_EMP_WHT_N1'
GROUP BY points
order by c.priority,b.priority,a.is_bool;";
var pointData = backendRepository.GetAllAsync<History_PostItem>(Sql).Result;
List<string> points = pointData.Select(x => x.points).ToList();
List<string> inputParams = post.Points;
inputParams.Sort((a, b) => points.IndexOf(a).CompareTo(points.IndexOf(b)));
foreach (var Device in post.Device_list) foreach (var Device in post.Device_list)
{ {
foreach (var point in post.Points) foreach (var point in inputParams)
{ {
DeviceNumberPoint deviceNumberPoint = new DeviceNumberPoint(); DeviceNumberPoint deviceNumberPoint = new DeviceNumberPoint();
deviceNumberPoint.DeviceNumber = Device; deviceNumberPoint.DeviceNumber = Device;
@ -1261,7 +1309,7 @@ namespace FrontendWebApi.ApiControllers
inner join variable v2 on temp.device_name_tag COLLATE utf8mb4_unicode_ci = v2.system_value and v2.deleted = 0 and v2.system_type = 'device_system_category_layer3' inner join variable v2 on temp.device_name_tag COLLATE utf8mb4_unicode_ci = v2.system_value and v2.deleted = 0 and v2.system_type = 'device_system_category_layer3'
order by b.priority, v1.system_priority, v2.system_priority, temp.priority;"; order by b.priority, v1.system_priority, v2.system_priority, temp.priority;";
var device_item_infos = await frontendRepository.GetAllAsync<DeviceItemInfo>(sqlDeviceItemInfo, new { Device_number = post.Device_list, points = post.Points}); var device_item_infos = await frontendRepository.GetAllAsync<DeviceItemInfo>(sqlDeviceItemInfo, new { Device_number = post.Device_list, points = post.Points });
if (post.Type == 1) if (post.Type == 1)
{ {
@ -1269,7 +1317,7 @@ namespace FrontendWebApi.ApiControllers
//轉換日期格式 //轉換日期格式
var start = string.Format("{0}T{1}:00.000+08:00", post.Start_date, post.Start_time); var start = string.Format("{0}T{1}:00.000+08:00", post.Start_date, post.Start_time);
var end = string.Format("{0}T{1}:05.000+08:00", post.End_date, post.End_time); var end = string.Format("{0}T{1}:10.000+08:00", post.End_date, post.End_time);
var historyQueryFilter = $@"<obj is='obix: HistoryFilter'> var historyQueryFilter = $@"<obj is='obix: HistoryFilter'>
<abstime name = 'start' val = '{start}' /> <abstime name = 'start' val = '{start}' />
@ -1404,7 +1452,7 @@ namespace FrontendWebApi.ApiControllers
{ {
//轉換日期格式 //轉換日期格式
var start = string.Format("{0}T{1}:00.000+08:00", day.ToString("yyyy-MM-dd"), post.Start_time); var start = string.Format("{0}T{1}:00.000+08:00", day.ToString("yyyy-MM-dd"), post.Start_time);
var end = string.Format("{0}T{1}:05.000+08:00", day.ToString("yyyy-MM-dd"), post.End_time); var end = string.Format("{0}T{1}:10.000+08:00", day.ToString("yyyy-MM-dd"), post.End_time);
var historyQueryFilter = $@"<obj is='obix: HistoryFilter'> var historyQueryFilter = $@"<obj is='obix: HistoryFilter'>
<abstime name = 'start' val = '{start}' /> <abstime name = 'start' val = '{start}' />
@ -1530,13 +1578,15 @@ namespace FrontendWebApi.ApiControllers
#endregion #endregion
} }
historyRawDatas.Reverse(); var data = historyRawDatas.GroupBy(x => new { x.Device_number, x.Points })
var pagedDevices = historyRawDatas.Skip((pageNumber - 1) * pageSize).Take(pageSize); .SelectMany(g => g.OrderByDescending(x => x.Timestamp))
.ToList();
var pagedDevices = data.Skip((pageNumber - 1) * pageSize).Take(pageSize);
stopwatch.Stop(); stopwatch.Stop();
double elapsedTime = stopwatch.Elapsed.TotalSeconds; double elapsedTime = stopwatch.Elapsed.TotalSeconds;
var result = new PageResultT<HistoryRawData> var result = new PageResultT<HistoryRawData>
{ {
Items = historyRawDatas, Items = data,
PageNumber = pageNumber, PageNumber = pageNumber,
PageSize = pageSize, PageSize = pageSize,
TotalItems = totalItems, TotalItems = totalItems,