完成資料歷程匯出程序

This commit is contained in:
dev02 2022-11-25 12:32:32 +08:00
parent f5a3e6af2a
commit d8fd45e185
5 changed files with 190 additions and 122 deletions

View File

@ -42,31 +42,22 @@
</div> </div>
<div class="col-auto"> <div class="col-auto">
<a href="#" onclick="searchDate()" class="btn btn-info">查詢</a> <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> <span class="fal fa-file-excel mr-1"></span>
匯出 匯出
</a> </a>
</div> </div>
</div> </div>
<div class="row mb-2"> <div class="row col mb-2">
<div id="devPointsList" class="btn-group"> <div id="devPointsList" class="btn-group">
</div> </div>
</div> </div>
<div class="row"> <div class="col-md-4">
<div class="frame-wrap"> <div class="frame-wrap">
<table id="tableData" class="table table-bordered table-striped text-center m-0"> <table id="historyTable" class="table table-bordered table-striped text-center m-0 w-100">
<thead class="thead-themed">
<tr>
<th>設備名稱</th>
<th>數值</th>
<th>紀錄時間</th>
</tr>
</thead>
<tbody>
</tbody>
</table> </table>
</div> </div>
</div> </div>
@ -77,6 +68,7 @@
</main> </main>
<script> <script>
var historyTable = null;
$(function () { $(function () {
initList(); initList();
@ -90,6 +82,8 @@
initApp.listFilter($('#js_nested_list'), $('#js_nested_list_filter')); initApp.listFilter($('#js_nested_list'), $('#js_nested_list_filter'));
//init navigation //init navigation
initApp.buildNavigation($('#js_nested_list')); initApp.buildNavigation($('#js_nested_list'));
loadTable(null);
}); });
function initList() { function initList() {
@ -201,21 +195,15 @@
} }
function callBackFromHistory(res) { function callBackFromHistory(res) {
let strHtml = ``;
res = JSON.parse(res); res = JSON.parse(res);
if (res.data.length > 0) { loadTable(res.data);
$.each(res.data, function (index, val) { if (historyTable != null) {
strHtml += `<tr> let t = $('#historyTable').dataTable();
<td>${val.deviceName}</td>
<td>${val.value}</td>
<td>${displayDate(val.timestamp)}</td>
</tr>`;
});
}
else
strHtml += `<tr><td colspan="3">查無資料</td></tr>`;
$('#tableData tbody').html(strHtml); t.fnClearTable();
if (res.data.length > 0)
t.fnAddData(res.data);
}
} }
function setValue(deviceNumber, deviceName, deviceItem) { function setValue(deviceNumber, deviceName, deviceItem) {
@ -295,4 +283,42 @@
return month + "/" + day + "/" + year; 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();;
ytAjax = new YourTeam.Ajax(url, objSendData, function (rel) {
location.href = baseApiUrl + "/api/df?fileName=" + rel.data + "&token=" + localStorage.getItem("JWT-Authorization");
}, null, "POST").send();
}
</script> </script>

View File

@ -16,6 +16,9 @@ using System.Threading.Tasks;
using System.Xml; using System.Xml;
using NPOI.XSSF.UserModel; using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel; using NPOI.SS.UserModel;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.HPSF;
namespace FrontendWebApi.ApiControllers namespace FrontendWebApi.ApiControllers
{ {
@ -39,9 +42,28 @@ namespace FrontendWebApi.ApiControllers
/// </summary> /// </summary>
/// <param name="lhe"></param> /// <param name="lhe"></param>
/// <returns></returns> /// <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 fileName = "廠商資料.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設定 #region excel設定
IFont font12 = workbook.CreateFont(); IFont font12 = workbook.CreateFont();
font12.FontName = "新細明體"; font12.FontName = "新細明體";
@ -84,7 +106,7 @@ namespace FrontendWebApi.ApiControllers
stylein12.WrapText = true; stylein12.WrapText = true;
#endregion #endregion
var sheet = workbook.CreateSheet("歷史資料"); ISheet sheet = workbook.CreateSheet("歷史資料");
int RowPosition = 0; int RowPosition = 0;
#region set cell #region set cell
IRow row = sheet.CreateRow(RowPosition); IRow row = sheet.CreateRow(RowPosition);
@ -113,7 +135,7 @@ namespace FrontendWebApi.ApiControllers
cell = row.CreateCell(i); cell = row.CreateCell(i);
if (i == 0) if (i == 0)
{ {
cell.SetCellValue(he.device_name); cell.SetCellValue(he.deviceName);
} }
if (i == 1) if (i == 1)
{ {
@ -121,7 +143,7 @@ namespace FrontendWebApi.ApiControllers
} }
if (i == 2) if (i == 2)
{ {
cell.SetCellValue(he.record_time); cell.SetCellValue(he.timestamp.ToString("yyyy-MM-dd HH:mm") + ":00");//
} }
cell.CellStyle = style12; cell.CellStyle = style12;
@ -129,15 +151,20 @@ namespace FrontendWebApi.ApiControllers
} }
} }
var ms = new NpoiMemoryStream workbook.Write(fs);
{ }
AllowClose = false
};
workbook.Write(ms);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
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> /// <summary>

View File

@ -12,6 +12,7 @@ using Repository.BackendRepository.Interface;
using Repository.FrontendRepository.Interface; using Repository.FrontendRepository.Interface;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
@ -135,5 +136,19 @@ namespace FrontendWebApi.ApiControllers
return Ok(apiResult); 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,8 @@ namespace FrontendWebApi.Models
public class HistoryExport public class HistoryExport
{ {
public string device_name { get; set; } public string deviceName { get; set; }
public string value { get; set; } public int value { get; set; }
public string record_time { get; set; } public DateTime timestamp { get; set; }
} }
} }

Binary file not shown.