This commit is contained in:
dev01 2022-11-28 18:08:57 +08:00
commit 9da9ff177a
4 changed files with 210 additions and 129 deletions

View File

@ -42,31 +42,22 @@
</div>
<div class="col-auto">
<a href="#" onclick="searchDate()" class="btn btn-info">查詢</a>
<a href="#" class="btn btn-info waves-effect waves-themed">
<a href="#" onclick="exportExcel()" class="btn btn-info waves-effect waves-themed">
<span class="fal fa-file-excel mr-1"></span>
匯出
</a>
</div>
</div>
<div class="row mb-2">
<div class="row col mb-2">
<div id="devPointsList" class="btn-group">
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="frame-wrap">
<table id="tableData" class="table table-bordered table-striped text-center m-0">
<thead class="thead-themed">
<tr>
<th>設備名稱</th>
<th>數值</th>
<th>紀錄時間</th>
</tr>
</thead>
<tbody>
</tbody>
<table id="historyTable" class="table table-bordered table-striped text-center m-0 w-100">
</table>
</div>
</div>
@ -77,6 +68,7 @@
</main>
<script>
var historyTable = null;
$(function () {
initList();
@ -90,6 +82,9 @@
initApp.listFilter($('#js_nested_list'), $('#js_nested_list_filter'));
//init navigation
initApp.buildNavigation($('#js_nested_list'));
loadTable(null);
$(`[onclick="setDateType('today')"]`).click();
});
function initList() {
@ -192,30 +187,24 @@
var edt = new Date(new Date().setDate(sdt.getDate() + 1));
start = start ?? sdt.toLocaleDateString();
end = end ?? edt.toLocaleDateString();
getHistoryDataByBaja(pageAct.deviceNumber + "_" + pageAct.deviceItem,
new Date(start).getTime(),
new Date(end).getTime(),
pageAct.deviceName,
"Mitsubishi_Sup",
callBackFromHistory);
// getHistoryDataByBaja(pageAct.deviceNumber + "_" + pageAct.deviceItem,
//new Date(start).getTime(),
//new Date(end).getTime(),
//pageAct.deviceName,
// "Mitsubishi_Sup",
// callBackFromHistory);
}
function callBackFromHistory(res) {
let strHtml = ``;
res = JSON.parse(res);
if (res.data.length > 0) {
$.each(res.data, function (index, val) {
strHtml += `<tr>
<td>${val.deviceName}</td>
<td>${val.value}</td>
<td>${displayDate(val.timestamp)}</td>
</tr>`;
});
}
else
strHtml += `<tr><td colspan="3">查無資料</td></tr>`;
loadTable(res.data);
if (historyTable != null) {
let t = $('#historyTable').dataTable();
$('#tableData tbody').html(strHtml);
t.fnClearTable();
if (res.data.length > 0)
t.fnAddData(res.data);
}
}
function setValue(deviceNumber, deviceName, deviceItem) {
@ -295,4 +284,50 @@
return month + "/" + day + "/" + year;
}
}
function loadTable(data) {
let tag = "#historyTable";
let column_defs = [
{ "targets": [0], "width": "20%", "sortable": true },
{ "targets": [1], "width": "20%", "sortable": true },
{ "targets": [2], "width": "20%", "sortable": true }
];
let columns = [
{
"title": "設備名稱",
"data": "deviceName",
},
{
"title": "數值",
"data": "value",
},
{
"title": "紀錄時間",
"data": "timestamp",
"render": function (date) {
return displayDate(date, "datetime");
}
}
];
historyTable = new YourTeam.JqDataTables.getTableByStatic(tag, data, columns, column_defs, null, null, null, null, "tpi");
}
function exportExcel() {
let url = baseApiUrl + "/History/OpeExportExcel";
objSendData.Data = $('#historyTable').dataTable().fnGetData();
$.each(objSendData.Data, function (i, v) {
v.starttime = (pageAct.dateType == "month" ? new Date($('#getmonth').val()) : new Date($('#startdate').val()));
v.endtime = $('#enddate input').val() === "" ? null : new Date($('#enddate input').val());
v.dateType = pageAct.dateType;
});
ytAjax = new YourTeam.Ajax(url, objSendData, function (rel) {
if (rel.code == "0000")
location.href = baseApiUrl + "/api/df?fileName=" + rel.data + "&token=" + localStorage.getItem("JWT-Authorization");
}, null, "POST").send();
}
</script>

View File

@ -16,6 +16,9 @@ using System.Threading.Tasks;
using System.Xml;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.HPSF;
namespace FrontendWebApi.ApiControllers
{
@ -39,9 +42,29 @@ namespace FrontendWebApi.ApiControllers
/// </summary>
/// <param name="lhe"></param>
/// <returns></returns>
public FileResult OpeExportExcel([FromBody] List<HistoryExport> lhe)
public ActionResult<ApiResult<string>> OpeExportExcel([FromBody] List<HistoryExport> lhe)
{
var workbook = new XSSFWorkbook();
ApiResult<string> apiResult = new ApiResult<string>();
if (lhe == null)
{
apiResult.Code = "0001";
apiResult.Msg = "沒有資料匯入";
return apiResult;
}
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");
var fileName = "廠商資料_"+fileDateName+".xlsx";
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設定
IFont font12 = workbook.CreateFont();
font12.FontName = "新細明體";
@ -84,7 +107,7 @@ namespace FrontendWebApi.ApiControllers
stylein12.WrapText = true;
#endregion
var sheet = workbook.CreateSheet("歷史資料");
ISheet sheet = workbook.CreateSheet("歷史資料");
int RowPosition = 0;
#region set cell
IRow row = sheet.CreateRow(RowPosition);
@ -113,7 +136,7 @@ namespace FrontendWebApi.ApiControllers
cell = row.CreateCell(i);
if (i == 0)
{
cell.SetCellValue(he.device_name);
cell.SetCellValue(he.deviceName);
}
if (i == 1)
{
@ -121,7 +144,7 @@ namespace FrontendWebApi.ApiControllers
}
if (i == 2)
{
cell.SetCellValue(he.record_time);
cell.SetCellValue(he.timestamp.ToString("yyyy-MM-dd HH:mm") + ":00");//
}
cell.CellStyle = style12;
@ -129,15 +152,20 @@ namespace FrontendWebApi.ApiControllers
}
}
var ms = new NpoiMemoryStream
{
AllowClose = false
};
workbook.Write(ms);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
workbook.Write(fs);
}
return File(ms, "application/vnd.ms-excel", "廠商資料.xlsx");
apiResult.Code = "0000";
apiResult.Data = fileName;
}
catch (Exception exception)
{
apiResult.Code = "9999";
apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Ok(apiResult);
}
return Ok(apiResult);
}
/// <summary>

View File

@ -12,6 +12,7 @@ using Repository.BackendRepository.Interface;
using Repository.FrontendRepository.Interface;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net;
@ -135,5 +136,19 @@ namespace FrontendWebApi.ApiControllers
return Ok(apiResult);
}
[HttpGet]
[Route("api/df")]
public ActionResult DownloadFile(string fileName, string token)
{
var jwt = new JwtSecurityTokenHandler().ReadJwtToken(token);
if (jwt == null)
return Unauthorized(HttpStatusCode.Unauthorized);
else if (fileName == null)
return NotFound("找不到文件");
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "excel", "history");
return File(System.IO.File.ReadAllBytes(Path.Combine(filePath, fileName)), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
}
}
}

View File

@ -265,8 +265,11 @@ namespace FrontendWebApi.Models
public class HistoryExport
{
public string device_name { get; set; }
public string value { get; set; }
public string record_time { get; set; }
public string deviceName { get; set; }
public int value { get; set; }
public DateTime timestamp { get; set; }
public DateTime starttime { get; set; }
public DateTime? endtime { get; set; }
public string dateType { get; set; }
}
}