[後端] 修改歷史資料下載方式, 修改報表匯出錯誤

[前端] 修改歷史資料時間發送問題
This commit is contained in:
dev02 2023-07-04 16:45:03 +08:00
parent 6ca824e00c
commit 54e295628f
3 changed files with 192 additions and 134 deletions

View File

@ -280,18 +280,32 @@
$('#devPointsList').html(strHtml); $('#devPointsList').html(strHtml);
if (!hisFirst) if (!hisFirst) {
getData(); let start = new Date($('#his_startdate').val());
let end = new Date(new Date().setDate(new Date($('#his_enddate input').val()).getDate() + 1));
if (pageAct.dateType == "today" || pageAct.dateType == "day" || pageAct.dateType == "ytd")
end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 1));
else if (pageAct.dateType == "month") {
start = new Date($('#getmonth').val());
end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 30));
}
else if (pageAct.dateType != "range")
return;
getData(formatDate(start, "date", true), formatDate(end, "date", true));
}
} }
ytAjax = new YourTeam.Ajax(url, objSendData, success, null, "POST").send(); ytAjax = new YourTeam.Ajax(url, objSendData, success, null, "POST").send();
} }
function getData(start = null, end = null) { function getData(start = null, end = null) {
$(loadEle).Loading("start");
var sdt = new Date(); var sdt = new Date();
var edt = new Date(new Date().setDate(sdt.getDate() + 1)); var edt = new Date(new Date().setDate(sdt.getDate() + 1));
start = start ?? sdt.toLocaleDateString(); start = start ?? sdt.toLocaleDateString();
end = end ?? edt.toLocaleDateString(); end = end ?? edt.toLocaleDateString();
callBackFromHistory(); // callBackFromHistory();
getHistoryDataByBaja(pageAct.deviceNumber + "_" + pageAct.deviceItem, getHistoryDataByBaja(pageAct.deviceNumber + "_" + pageAct.deviceItem,
new Date(start).getTime(), new Date(start).getTime(),
new Date(end).getTime(), new Date(end).getTime(),
@ -329,13 +343,13 @@
let end = new Date(new Date().setDate(new Date($('#his_enddate input').val()).getDate() + 1)); let end = new Date(new Date().setDate(new Date($('#his_enddate input').val()).getDate() + 1));
if (pageAct.dateType == "today" || pageAct.dateType == "day" || pageAct.dateType == "ytd") if (pageAct.dateType == "today" || pageAct.dateType == "day" || pageAct.dateType == "ytd")
end = new Date(new Date().setDate(start.getDate() + 1)); end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 1));
else if (pageAct.dateType == "month") { else if (pageAct.dateType == "month") {
start = new Date($('#getmonth').val()); start = new Date($('#getmonth').val());
end = new Date(new Date().setDate(start.getDate() + 30)); end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 30));
} }
else if (pageAct.dateType != "range") else if (pageAct.dateType != "range")
getData(); return;
getData(formatDate(start, "date", true), formatDate(end, "date", true)); getData(formatDate(start, "date", true), formatDate(end, "date", true));
} }
@ -399,10 +413,10 @@
let end = new Date(new Date().setDate(new Date($('#his_enddate input').val()).getDate() + 1)); let end = new Date(new Date().setDate(new Date($('#his_enddate input').val()).getDate() + 1));
if (pageAct.dateType == "today" || pageAct.dateType == "day" || pageAct.dateType == "ytd") if (pageAct.dateType == "today" || pageAct.dateType == "day" || pageAct.dateType == "ytd")
end = new Date(new Date().setDate(start.getDate() + 1)); end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 1));
else if (pageAct.dateType == "month") { else if (pageAct.dateType == "month") {
start = new Date($('#getmonth').val()); start = new Date($('#getmonth').val());
end = new Date(new Date().setDate(start.getDate() + 30)); end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 30));
} }
else if (pageAct.dateType != "range") else if (pageAct.dateType != "range")
return; return;
@ -471,21 +485,48 @@
function exportExcel() { function exportExcel() {
$(loadEle).Loading("start"); $(loadEle).Loading("start");
let url = baseApiUrl + "/History/OpeExportExcel"; let token = cookies.get("JWT-Authorization");
let url = baseApiUrl + "/api/ExportHistory";
let v = {}; let v = {};
v.starttime = (pageAct.dateType == "month" ? new Date($('#getmonth').val()) : new Date($('#his_startdate').val())); v.starttime = (pageAct.dateType == "month" ? new Date($('#getmonth').val()) : new Date($('#his_startdate').val()));
v.endtime = $('#his_enddate input').val() === "" ? null : new Date($('#his_enddate input').val()); v.endtime = $('#his_enddate input').val() === "" ? null : new Date($('#his_enddate input').val());
v.dateType = pageAct.dateType; v.dateType = pageAct.dateType;
objSendData.Data = v; objSendData.Data = v;
ytAjax = new YourTeam.Ajax(url, objSendData, function (rel) { $.ajax({
if (rel.code == "0000") type: "POST",
location.href = baseApiUrl + "/api/df?path=" + rel.data.split('/')[0] + "&fileName=" + rel.data.split('/')[1] + "&token=" + cookies.get("JWT-Authorization"); url: url,
data: JSON.stringify(objSendData.Data),
aysnc: true,
headers: {
Authorization: "Bearer " + token,
},
contentType: "application/json; charset=utf-8",
xhrFields: {
responseType: "blob", // to avoid binary data being mangled on charset conversion
},
success: function (rel, text, xhr) {
if (rel) {
downloadByBlob(xhr, rel);
}
$(loadEle).Loading("close");
},
error: function () {
$(loadEle).Loading("close");
},
complete: (xhr) => {
setLoading(false);
},
});
// ytAjax = new YourTeam.Ajax(url, objSendData, function (rel) {
// $(loadEle).Loading("close");
// }, function (rel) {
// if (rel) {
// downloadByBlob(xhr, rel);
// }
$(loadEle).Loading("close"); // $(loadEle).Loading("close");
}, () => { // }, "POST",true).send();
$(loadEle).Loading("close");
}, "POST", true).send();
} }
//選擇棟別 //選擇棟別

View File

@ -1,9 +1,11 @@
using FrontendWebApi.Models; using FrontendWebApi.Models;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using NPOI.HPSF;
using NPOI.SS.UserModel; using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel; using NPOI.XSSF.UserModel;
using Repository.BackendRepository.Interface; using Repository.BackendRepository.Interface;
@ -45,35 +47,40 @@ namespace FrontendWebApi.ApiControllers
/// <param name="lhe"></param> /// <param name="lhe"></param>
/// <returns></returns> /// <returns></returns>
[HttpPost] [HttpPost]
public async Task<ActionResult<ApiResult<string>>> OpeExportExcel([FromBody] HistoryExport lhe) [Route("api/ExportHistory")]
public FileResult OpeExportExcel([FromBody] HistoryExport lhe)
{ {
ApiResult<string> apiResult = new ApiResult<string>(); ApiResult<string> apiResult = new ApiResult<string>();
if (lhe == null) //if (lhe == null)
{ //{
apiResult.Code = "0001"; // apiResult.Code = "0001";
apiResult.Msg = "沒有資料匯入"; // apiResult.Msg = "沒有資料匯入";
return apiResult; // return apiResult;
} //}
var fileDateName = lhe.dateType == "today" ? lhe.starttime.ToString("yyyy-MM-dd")
: lhe.dateType == "month" ? lhe.starttime.ToString("yyyy-MM")
: lhe.starttime.ToString("yyyy-MM-dd") + "_" + ((DateTime)lhe.endtime).ToString("yyyy-MM-dd");
var fileName = "歷史資料_" + fileDateName + ".xlsx";
XSSFWorkbook workbook = new XSSFWorkbook();
try try
{ {
#region obix #region obix
EDFunction ed = new EDFunction(); EDFunction ed = new EDFunction();
var obixApiConfig = new ObixApiConfig(); var obixApiConfig = new ObixApiConfig();
var sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'"; var sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'";
var variableObix = await backendRepository.GetAllAsync<KeyValue>(sqlObix); var variableObix = backendRepository.GetAllAsync<KeyValue>(sqlObix).Result;
obixApiConfig.ApiBase = variableObix.Where(x => x.Name == "ApiBase").Select(x => x.Value).FirstOrDefault(); obixApiConfig.ApiBase = variableObix.Where(x => x.Name == "ApiBase").Select(x => x.Value).FirstOrDefault();
obixApiConfig.UserName = ed.AESDecrypt(variableObix.Where(x => x.Name == "UserName").Select(x => x.Value).FirstOrDefault()); obixApiConfig.UserName = ed.AESDecrypt(variableObix.Where(x => x.Name == "UserName").Select(x => x.Value).FirstOrDefault());
obixApiConfig.Password = ed.AESDecrypt(variableObix.Where(x => x.Name == "Password").Select(x => x.Value).FirstOrDefault()); obixApiConfig.Password = ed.AESDecrypt(variableObix.Where(x => x.Name == "Password").Select(x => x.Value).FirstOrDefault());
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(obixApiConfig.UserName + ":" + obixApiConfig.Password)); String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(obixApiConfig.UserName + ":" + obixApiConfig.Password));
#endregion obix #endregion obix
var building = await backendRepository.GetAllAsync<BuildList>("select * from building where deleted = 0"); var building = backendRepository.GetAllAsync<BuildList>("select * from building where deleted = 0").Result;
var buildStation = await backendRepository.GetAllAsync<BuildStation>("select SUBSTRING_INDEX(system_value, '/', 1) system_value, system_key from variable where system_type = 'dashboard_total_elec' and deleted = 0 and (SUBSTRING_INDEX(system_value, '/', 1) != '' and SUBSTRING_INDEX(system_value, '/', 1) is not null)"); var buildStation = backendRepository.GetAllAsync<BuildStation>("select SUBSTRING_INDEX(system_value, '/', 1) system_value, system_key from variable where system_type = 'dashboard_total_elec' and deleted = 0 and (SUBSTRING_INDEX(system_value, '/', 1) != '' and SUBSTRING_INDEX(system_value, '/', 1) is not null)").Result;
#region get device and device_item(point) #region get device and device_item(point)
var device = await backendRepository.GetAllAsync<Device>($"select * from device where deleted = 0 and is_link = 1 and device_building_tag in ('{string.Join("','", building.Select(x => x.building_tag))}')"); var device = backendRepository.GetAllAsync<Device>($"select * from device where deleted = 0 and is_link = 1 and device_building_tag in ('{string.Join("','", building.Select(x => x.building_tag))}')").Result;
var devicePoint = await backendRepository.GetAllAsync<Device_item>($"select * from device_item where deleted = 0 and is_link = 1 and is_show_history = 1 and device_building_tag in ('{string.Join("','", building.Select(x => x.building_tag))}')"); var devicePoint = backendRepository.GetAllAsync<Device_item>($"select * from device_item where deleted = 0 and is_link = 1 and is_show_history = 1 and device_building_tag in ('{string.Join("','", building.Select(x => x.building_tag))}')").Result;
#endregion #endregion
List<DeviceNumberPoint> listDevicePoint = new List<DeviceNumberPoint>(); List<DeviceNumberPoint> listDevicePoint = new List<DeviceNumberPoint>();
@ -166,18 +173,12 @@ namespace FrontendWebApi.ApiControllers
#endregion #endregion
#region export file progress #region export file progress
var fileDateName = lhe.dateType == "today" ? lhe.starttime.ToString("yyyy-MM-dd") //var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "excel", "history");
: lhe.dateType == "month" ? lhe.starttime.ToString("yyyy-MM")
: lhe.starttime.ToString("yyyy-MM-dd") + "_" + ((DateTime)lhe.endtime).ToString("yyyy-MM-dd"); //if (!System.IO.Directory.Exists(filePath))
var fileName = "歷史資料_" + fileDateName + ".xlsx"; // System.IO.Directory.CreateDirectory(filePath);
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "excel", "history");
if (!System.IO.Directory.Exists(filePath))
System.IO.Directory.CreateDirectory(filePath);
using (var fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create, FileAccess.Write))
{
IWorkbook workbook = new XSSFWorkbook();
#region excel設定 #region excel設定
IFont font12 = workbook.CreateFont(); IFont font12 = workbook.CreateFont();
font12.FontName = "新細明體"; font12.FontName = "新細明體";
@ -275,21 +276,37 @@ namespace FrontendWebApi.ApiControllers
} }
} }
} }
workbook.Write(fs);
}
//using (var fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create, FileAccess.Write))
//{
//workbook.Write(fs);
//}
#endregion #endregion
apiResult.Code = "0000"; //apiResult.Code = "0000";
apiResult.Data = "history/" + fileName; //apiResult.Data = "history/" + fileName;
} }
catch (Exception exception) catch (Exception exception)
{ {
apiResult.Code = "9999"; apiResult.Code = "9999";
apiResult.Msg = "系統內部錯誤,請聯絡管理者。 Msg: " + exception.Message; apiResult.Msg = "系統內部錯誤,請聯絡管理者。 Msg: " + exception.Message;
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Ok(apiResult); throw exception;
} }
return Ok(apiResult);
var ms = new NpoiMemoryStream
{
AllowClose = false
};
workbook.Write(ms);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
return File(ms, "application/vnd.ms-excel", fileName);
} }
/// <summary> /// <summary>

View File

@ -461,12 +461,12 @@ namespace FrontendWebApi.ApiControllers
stylein12.WrapText = true; stylein12.WrapText = true;
#endregion #endregion
foreach (var r in result) foreach (var r in result)
{
if (r.Count > 0)
{ {
string buildingName = r.Select(x => x.building_name).FirstOrDefault(); string buildingName = r.Select(x => x.building_name).FirstOrDefault();
var sheet = workbook.CreateSheet($"{buildingName}電表報表"); var sheet = workbook.CreateSheet($"{buildingName}電表報表");
int RowPosition = 0; int RowPosition = 0;
if (result.Count > 0)
{
#region set cell #region set cell
IRow row = sheet.CreateRow(RowPosition); IRow row = sheet.CreateRow(RowPosition);
sheet.SetColumnWidth(0, 4 * 160 * 12); sheet.SetColumnWidth(0, 4 * 160 * 12);