[後端] 排程修改錯誤log部分, 修改歷史資料匯出

[前端] 修改baja.js, 修改歷史資料程序
This commit is contained in:
dev02 2023-07-17 15:23:13 +08:00
parent 949b9407af
commit 3e8daf7759
4 changed files with 289 additions and 240 deletions

View File

@ -1360,28 +1360,98 @@ namespace BackendWorkerService.Quartz.Jobs
private List<Dictionary<string, object>> ArrangeRawData(DeviceNumberPoint deviceNumberPoint, JObject jsonResult) private List<Dictionary<string, object>> ArrangeRawData(DeviceNumberPoint deviceNumberPoint, JObject jsonResult)
{ {
List<Dictionary<string, object>> arrangeRawDatas = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> arrangeRawDatas = new List<Dictionary<string, object>>();
var histories = jsonResult["obj"]["list"]; try
var rawdateCount = Convert.ToInt32(jsonResult["obj"]["int"]["@val"].ToString());
if(rawdateCount == 0)
{ {
return null; var histories = jsonResult["obj"]["list"];
} var rawdateCount = Convert.ToInt32(jsonResult["obj"]["int"]["@val"].ToString());
if (histories != null && histories.HasValues) if (rawdateCount == 0)
{ {
if (rawdateCount > 1) return null;
{ //多筆資料 }
foreach (var history in histories)
{ if (histories != null && histories.HasValues)
{
if (rawdateCount > 1)
{ //多筆資料
foreach (var history in histories)
{
Dictionary<string, object> arrangeRawData = new Dictionary<string, object>();
arrangeRawData.Add("@device_number", deviceNumberPoint.DeviceNumber);
arrangeRawData.Add("@point", deviceNumberPoint.Point);
//時間
if (history["abstime"] != null && history["abstime"].HasValues)
{
foreach (var abstime in history["abstime"])
{
var name = abstime["@name"].ToString();
switch (name)
{
case "start":
var startTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@start_timestamp", startTimstamp);
break;
case "end":
var endTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@end_timestamp", endTimstamp);
break;
}
}
}
//區間內資料筆數
if (history["int"] != null && history["int"].HasValues)
{
var count = Convert.ToInt32(histories["obj"]["int"]["@val"].ToString());
arrangeRawData.Add("@count_rawdata", count);
}
//整合數值(最大、最小、平均、總和)
if (history["real"] != null && history["real"].HasValues)
{
foreach (var real in history["real"])
{
var name = real["@name"].ToString();
switch (name)
{
case "min":
var min = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@min_rawdata", min);
break;
case "max":
var max = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@max_rawdata", max);
break;
case "avg":
var avg = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@avg_rawdata", avg);
break;
case "sum":
var sum = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@sum_rawdata", sum);
break;
}
}
}
arrangeRawData.Add("@is_complete", 1);
arrangeRawData.Add("@repeat_times", 0);
arrangeRawData.Add("@fail_reason", null);
arrangeRawData.Add("@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
arrangeRawDatas.Add(arrangeRawData);
}
}
else
{ //單筆資料
Dictionary<string, object> arrangeRawData = new Dictionary<string, object>(); Dictionary<string, object> arrangeRawData = new Dictionary<string, object>();
arrangeRawData.Add("@device_number", deviceNumberPoint.DeviceNumber); arrangeRawData.Add("@device_number", deviceNumberPoint.DeviceNumber);
arrangeRawData.Add("@point", deviceNumberPoint.Point); arrangeRawData.Add("@point", deviceNumberPoint.Point);
//時間 //時間
if (history["abstime"] != null && history["abstime"].HasValues) if (histories["obj"]["abstime"] != null && histories["obj"]["abstime"].HasValues)
{ {
foreach (var abstime in history["abstime"]) foreach (var abstime in histories["obj"]["abstime"])
{ {
var name = abstime["@name"].ToString(); var name = abstime["@name"].ToString();
switch (name) switch (name)
@ -1399,16 +1469,16 @@ namespace BackendWorkerService.Quartz.Jobs
} }
//區間內資料筆數 //區間內資料筆數
if (history["int"] != null && history["int"].HasValues) if (histories["obj"]["int"] != null && histories["obj"]["int"].HasValues)
{ {
var count = Convert.ToInt32(histories["obj"]["int"]["@val"].ToString()); var count = Convert.ToInt32(histories["obj"]["int"]["@val"].ToString());
arrangeRawData.Add("@count_rawdata", count); arrangeRawData.Add("@count_rawdata", count);
} }
//整合數值(最大、最小、平均、總和) //整合數值(最大、最小、平均、總和)
if (history["real"] != null && history["real"].HasValues) if (histories["obj"]["real"] != null && histories["obj"]["real"].HasValues)
{ {
foreach (var real in history["real"]) foreach (var real in histories["obj"]["real"])
{ {
var name = real["@name"].ToString(); var name = real["@name"].ToString();
switch (name) switch (name)
@ -1440,76 +1510,13 @@ namespace BackendWorkerService.Quartz.Jobs
arrangeRawDatas.Add(arrangeRawData); arrangeRawDatas.Add(arrangeRawData);
} }
} }
else
{ //單筆資料
Dictionary<string, object> arrangeRawData = new Dictionary<string, object>();
arrangeRawData.Add("@device_number", deviceNumberPoint.DeviceNumber);
arrangeRawData.Add("@point", deviceNumberPoint.Point);
//時間 return arrangeRawDatas;
if (histories["obj"]["abstime"] != null && histories["obj"]["abstime"].HasValues) }
{ catch (Exception ex)
foreach (var abstime in histories["obj"]["abstime"]) {
{ return arrangeRawDatas;
var name = abstime["@name"].ToString();
switch (name)
{
case "start":
var startTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@start_timestamp", startTimstamp);
break;
case "end":
var endTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@end_timestamp", endTimstamp);
break;
}
}
}
//區間內資料筆數
if (histories["obj"]["int"] != null && histories["obj"]["int"].HasValues)
{
var count = Convert.ToInt32(histories["obj"]["int"]["@val"].ToString());
arrangeRawData.Add("@count_rawdata", count);
}
//整合數值(最大、最小、平均、總和)
if (histories["obj"]["real"] != null && histories["obj"]["real"].HasValues)
{
foreach (var real in histories["obj"]["real"])
{
var name = real["@name"].ToString();
switch (name)
{
case "min":
var min = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@min_rawdata", min);
break;
case "max":
var max = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@max_rawdata", max);
break;
case "avg":
var avg = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@avg_rawdata", avg);
break;
case "sum":
var sum = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@sum_rawdata", sum);
break;
}
}
}
arrangeRawData.Add("@is_complete", 1);
arrangeRawData.Add("@repeat_times", 0);
arrangeRawData.Add("@fail_reason", null);
arrangeRawData.Add("@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
arrangeRawDatas.Add(arrangeRawData);
}
} }
return arrangeRawDatas;
} }
} }
} }

View File

@ -70,6 +70,7 @@
<script> <script>
var historyTable = null; var historyTable = null;
hisFirst = true;
$(function () { $(function () {
initList(); initList();
@ -250,48 +251,61 @@
pageAct.deviceItem = val.points; pageAct.deviceItem = val.points;
pageAct.devicePoiName = val.full_name + ' ' + val.points; pageAct.devicePoiName = val.full_name + ' ' + val.points;
pageAct.deviceComName = val.parent_path; pageAct.deviceComName = val.parent_path;
getData();
} else { } else {
strHtml += `<button onClick="setValue(null, null, '${val.points}', this)" type="button" class="btn btn-secondary waves-effect waves-themed">${val.full_name || val.points}</button>`; strHtml += `<button onClick="setValue(null, null, '${val.points}', this)" type="button" class="btn btn-secondary waves-effect waves-themed">${val.full_name || val.points}</button>`;
} }
}); });
$('#devPointsList').html(strHtml); $('#devPointsList').html(strHtml);
if (!hisFirst) {
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) {
var sdt = new Date(); $(loadEle).Loading("start");
var edt = new Date(new Date().setDate(sdt.getDate() + 1)); var sdt = new Date();
$(loadEle).Loading("start"); 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(),
pageAct.deviceName, pageAct.deviceName,
pageAct.deviceComName, pageAct.deviceComName,
callBackFromHistory); callBackFromHistory);
} }
function callBackFromHistory(res = '{"count":0,"data":[]}') { function callBackFromHistory(res = '{"count":0,"data":[]}') {
// console.log("@H1",res) res = JSON.parse(res);
res = JSON.parse(res); loadTable(res.data);
// console.log("@history",res.data) if (historyTable != null) {
loadTable(res.data); let t = $('#historyTable').dataTable();
if (historyTable != null) { t.fnClearTable();
let t = $('#historyTable').dataTable(); if (res.data.length > 0)
t.fnAddData(res.data);
t.fnClearTable(); }
if (res.data.length > 0)
t.fnAddData(res.data);
}
$(loadEle).Loading("close");
} }
function setValue(deviceNumber, deviceName, deviceItem, elem) { function setValue(deviceNumber, deviceName, deviceItem, elem) {
hisFirst = false;
btnSelCss(elem); btnSelCss(elem);
if ((deviceNumber != null && deviceNumber != undefined) && (deviceName != null && deviceName != undefined)) { if ((deviceNumber != null && deviceNumber != undefined) && (deviceName != null && deviceName != undefined)) {
@ -302,7 +316,20 @@
else if (deviceItem != null && deviceItem != undefined) { else if (deviceItem != null && deviceItem != undefined) {
pageAct.devicePoiName = $(elem).text(); pageAct.devicePoiName = $(elem).text();
pageAct.deviceItem = deviceItem; pageAct.deviceItem = deviceItem;
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));
} }
} }
@ -314,7 +341,7 @@
let ytd = formatDate(new Date(new Date().setDate(new Date().getDate() - 1)), "date"); let ytd = formatDate(new Date(new Date().setDate(new Date().getDate() - 1)), "date");
let tmr = formatDate(new Date(new Date().setDate(new Date().getDate() + 1)), "date"); let tmr = formatDate(new Date(new Date().setDate(new Date().getDate() + 1)), "date");
if (type == "day" || type == "today" || type == "ytd") { if (type == "day" || type == "today" || type == "ytd") {
let date = type == "ytd" ? ytd : now; let date = type == "ytd" ? ytd : now;
$('#his_startdate').css('display', 'block'); $('#his_startdate').css('display', 'block');
$('#his_enddate').css('display', 'none'); $('#his_enddate').css('display', 'none');
@ -360,19 +387,19 @@
} }
function searchDate() { function searchDate() {
let start = new Date($('#his_startdate').val()); let start = new Date($('#his_startdate').val());
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")
end = new Date(new Date().setDate(start.getDate() + 1));
else if (pageAct.dateType == "month") {
start = new Date($('#getmonth').val());
end = new Date(new Date().setDate(start.getDate() + 30));
}
else if (pageAct.dateType != "range")
return;
getData(formatDate(start, "date", true), formatDate(end, "date", true)); 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));
} }
function formatDate(date, type, send = false) { function formatDate(date, type, send = false) {
@ -390,7 +417,6 @@
function loadTable(data) { function loadTable(data) {
if (data) { if (data) {
$.each(data, function (i, v) { $.each(data, function (i, v) {
// console.log("loadTable",pageAct.devicePoiName.split(" ")[0])
v.type = pageAct.devicePoiName.split(" ")[0]; v.type = pageAct.devicePoiName.split(" ")[0];
}); });
@ -425,7 +451,6 @@
"title": "紀錄時間", "title": "紀錄時間",
"data": "timestamp", "data": "timestamp",
"render": function (data) { "render": function (data) {
// console.log(data)
return displayDate(data, "datetime"); return displayDate(data, "datetime");
} }
} }
@ -437,20 +462,39 @@
} }
function exportExcel() { function exportExcel() {
$(loadEle).Loading("start"); $(loadEle).Loading("start");
let url = baseApiUrl + "/History/OpeExportExcel"; let token = cookies.get("JWT-Authorization");
objSendData.Data = $('#historyTable').dataTable().fnGetData(); let url = baseApiUrl + "/api/ExportHistory";
let v = {};
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.dateType = pageAct.dateType;
objSendData.Data = v;
$.each(objSendData.Data, function (i, v) { $.ajax({
v.starttime = (pageAct.dateType == "month" ? new Date($('#getmonth').val()) : new Date($('#his_startdate').val())); type: "POST",
v.endtime = $('#his_enddate input').val() === "" ? null : new Date($('#his_enddate input').val()); url: url,
v.dateType = pageAct.dateType; data: JSON.stringify(objSendData.Data),
}); aysnc: true,
ytAjax = new YourTeam.Ajax(url, objSendData, function (rel) { headers: {
if (rel.code == "0000") { Authorization: "Bearer " + token,
location.href = baseApiUrl + "/api/df?path=" + rel.data.split('/')[0] + "&fileName=" + rel.data.split('/')[1] + "&token=" + cookies.get("JWT-Authorization"); },
} contentType: "application/json; charset=utf-8",
}, null, "POST").send(); xhrFields: {
$(loadEle).Loading("close"); 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);
},
});
} }
</script> </script>

View File

@ -57,6 +57,7 @@ function getHistoryDataByBaja(devicePath, startDate_millisecond, endDate_millise
_index++; _index++;
}, },
after: function () { after: function () {
$(loadEle).Loading("close");
_result={count: _index, data: _ss} _result={count: _index, data: _ss}
// _result += '{' + '"count": ' + _index + ', "data":['; // _result += '{' + '"count": ' + _index + ', "data":[';
// _result += _ss; // _result += _ss;
@ -73,6 +74,7 @@ function getHistoryDataByBaja(devicePath, startDate_millisecond, endDate_millise
}) })
.catch(()=>{ .catch(()=>{
console.log("error"); console.log("error");
$(loadEle).Loading("close");
// const res = JSON.stringify({count:0, data:[]}) // const res = JSON.stringify({count:0, data:[]})
callback() callback()
}); });

View File

@ -58,117 +58,104 @@ namespace FrontendWebApi.ApiControllers
return apiResult; return apiResult;
} }
IWorkbook workbook = new XSSFWorkbook();
var fileDateName = lhe.FirstOrDefault().dateType == "month" ? lhe.FirstOrDefault().starttime.ToString("yyyy-MM") : lhe.FirstOrDefault().endtime == null ? lhe.FirstOrDefault().starttime.ToString("yyyy-MM-dd") : lhe.FirstOrDefault().starttime.ToString("yyyy-MM-dd") + "_" + ((DateTime)lhe.FirstOrDefault().endtime).ToString("yyyy-MM-dd");
var fileName = "歷史資料_"+fileDateName+".xlsx";
try try
{ {
var fileDateName = lhe.FirstOrDefault().dateType == "month" ? lhe.FirstOrDefault().starttime.ToString("yyyy-MM") : lhe.FirstOrDefault().endtime == null ? lhe.FirstOrDefault().starttime.ToString("yyyy-MM-dd") : lhe.FirstOrDefault().starttime.ToString("yyyy-MM-dd") + "_" + ((DateTime)lhe.FirstOrDefault().endtime).ToString("yyyy-MM-dd"); #region excel設定
var fileName = "歷史資料_"+fileDateName+".xlsx"; IFont font12 = workbook.CreateFont();
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "excel", "history"); font12.FontName = "新細明體";
font12.FontHeightInPoints = 12;
ICellStyle style12 = workbook.CreateCellStyle();
style12.SetFont(font12);
style12.Alignment = HorizontalAlignment.Center;
style12.VerticalAlignment = VerticalAlignment.Center;
IFont font12Times = workbook.CreateFont();
font12Times.FontName = "Times New Roman";
font12Times.FontHeightInPoints = 12;
IFont font18 = workbook.CreateFont();
font18.FontName = "新細明體";
font18.FontHeightInPoints = 18;
font18.IsBold = true;
ICellStyle styleTitle18 = workbook.CreateCellStyle();
styleTitle18.SetFont(font18);
styleTitle18.Alignment = HorizontalAlignment.Center;
styleTitle18.VerticalAlignment = VerticalAlignment.Center;
ICellStyle styleLeft12 = workbook.CreateCellStyle();
styleLeft12.SetFont(font12);
styleLeft12.Alignment = HorizontalAlignment.Left;
styleLeft12.VerticalAlignment = VerticalAlignment.Center;
ICellStyle styleLine12 = workbook.CreateCellStyle();
styleLine12.SetFont(font12);
styleLine12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
styleLine12.VerticalAlignment = VerticalAlignment.Center;
styleLine12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
ICellStyle stylein12 = workbook.CreateCellStyle();
stylein12.SetFont(font12Times);
stylein12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
stylein12.VerticalAlignment = VerticalAlignment.Center;
stylein12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.WrapText = true;
#endregion
if (!System.IO.Directory.Exists(filePath)) ISheet sheet = workbook.CreateSheet("歷史資料");
System.IO.Directory.CreateDirectory(filePath); int RowPosition = 0;
#region set cell
IRow row = sheet.CreateRow(RowPosition);
sheet.SetColumnWidth(0, 4 * 160 * 12);
sheet.SetColumnWidth(1, 4 * 160 * 12);
sheet.SetColumnWidth(2, 4 * 160 * 12);
sheet.SetColumnWidth(3, 4 * 160 * 12);
ICell cell = row.CreateCell(0);
cell.SetCellValue("類型");
cell.CellStyle = styleLine12;
cell = row.CreateCell(1);
cell.SetCellValue("設備名稱");
cell.CellStyle = styleLine12;
cell = row.CreateCell(2);
cell.SetCellValue("數值");
cell = row.CreateCell(3);
cell.SetCellValue("記錄時間");
cell.CellStyle = styleLine12;
#endregion
using (var fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create, FileAccess.Write)) if (lhe.Count > 0)
{ {
IWorkbook workbook = new XSSFWorkbook(); foreach (var he in lhe)
#region excel設定
IFont font12 = workbook.CreateFont();
font12.FontName = "新細明體";
font12.FontHeightInPoints = 12;
ICellStyle style12 = workbook.CreateCellStyle();
style12.SetFont(font12);
style12.Alignment = HorizontalAlignment.Center;
style12.VerticalAlignment = VerticalAlignment.Center;
IFont font12Times = workbook.CreateFont();
font12Times.FontName = "Times New Roman";
font12Times.FontHeightInPoints = 12;
IFont font18 = workbook.CreateFont();
font18.FontName = "新細明體";
font18.FontHeightInPoints = 18;
font18.IsBold = true;
ICellStyle styleTitle18 = workbook.CreateCellStyle();
styleTitle18.SetFont(font18);
styleTitle18.Alignment = HorizontalAlignment.Center;
styleTitle18.VerticalAlignment = VerticalAlignment.Center;
ICellStyle styleLeft12 = workbook.CreateCellStyle();
styleLeft12.SetFont(font12);
styleLeft12.Alignment = HorizontalAlignment.Left;
styleLeft12.VerticalAlignment = VerticalAlignment.Center;
ICellStyle styleLine12 = workbook.CreateCellStyle();
styleLine12.SetFont(font12);
styleLine12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
styleLine12.VerticalAlignment = VerticalAlignment.Center;
styleLine12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
ICellStyle stylein12 = workbook.CreateCellStyle();
stylein12.SetFont(font12Times);
stylein12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
stylein12.VerticalAlignment = VerticalAlignment.Center;
stylein12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.WrapText = true;
#endregion
ISheet sheet = workbook.CreateSheet("歷史資料");
int RowPosition = 0;
#region set cell
IRow row = sheet.CreateRow(RowPosition);
sheet.SetColumnWidth(0, 4 * 160 * 12);
sheet.SetColumnWidth(1, 4 * 160 * 12);
sheet.SetColumnWidth(2, 4 * 160 * 12);
sheet.SetColumnWidth(3, 4 * 160 * 12);
ICell cell = row.CreateCell(0);
cell.SetCellValue("類型");
cell.CellStyle = styleLine12;
cell = row.CreateCell(1);
cell.SetCellValue("設備名稱");
cell.CellStyle = styleLine12;
cell = row.CreateCell(2);
cell.SetCellValue("數值");
cell = row.CreateCell(3);
cell.SetCellValue("記錄時間");
cell.CellStyle = styleLine12;
#endregion
if (lhe.Count > 0)
{ {
foreach (var he in lhe) RowPosition += 1;
row = sheet.CreateRow(RowPosition);
for (var i = 0; i < 4; i++)
{ {
RowPosition += 1; cell = row.CreateCell(i);
row = sheet.CreateRow(RowPosition); if (i == 0)
for (var i = 0; i < 4; i++)
{ {
cell = row.CreateCell(i); cell.SetCellValue(he.type);
if (i == 0)
{
cell.SetCellValue(he.type);
}
if (i == 1)
{
cell.SetCellValue(he.deviceName);
}
if (i == 2)
{
cell.SetCellValue(he.value);
}
if (i == 3)
{
cell.SetCellValue(he.timestamp.ToString("yyyy-MM-dd HH:mm") + ":00");//
}
cell.CellStyle = style12;
} }
if (i == 1)
{
cell.SetCellValue(he.deviceName);
}
if (i == 2)
{
cell.SetCellValue(he.value);
}
if (i == 3)
{
cell.SetCellValue(he.timestamp.ToString("yyyy-MM-dd HH:mm") + ":00");//
}
cell.CellStyle = style12;
} }
} }
workbook.Write(fs);
} }
apiResult.Code = "0000";
apiResult.Data = "history/" + fileName;
} }
catch (Exception exception) catch (Exception exception)
{ {
@ -177,7 +164,16 @@ namespace FrontendWebApi.ApiControllers
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Ok(apiResult); return Ok(apiResult);
} }
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>