parking-webapi/WebApi_data_value/Services/ExcelGenerationService.cs
2024-09-28 01:25:42 +08:00

93 lines
3.6 KiB
C#

using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OfficeOpenXml;
using WebApi_data_value.Models;
using Microsoft.EntityFrameworkCore;
namespace Parking_space_WebAPI.Services
{
public class ExcelGenerationService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly string _saveDirectory = @"C:\Users\ste92\Desktop\parking-e\excel"; // 指定儲存 Excel 的資料夾
public ExcelGenerationService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await GenerateAndSaveExcel();
await Task.Delay(TimeSpan.FromHours(1), stoppingToken); // 每小時執行一次
//await Task.Delay(TimeSpan.FromMinutes(2), stoppingToken); // 每 2 分鐘執行一次
}
}
private async Task GenerateAndSaveExcel()
{
using (var scope = _serviceProvider.CreateScope())
{
var _context = scope.ServiceProvider.GetRequiredService<SqlContext>();
// 從資料庫讀取數據
var parkingSpaces = await _context.yuntech_parking.ToListAsync();
var monthlyRent = await _context.yuntech_monthly_rent_number
.FirstOrDefaultAsync(x => x.category == "月租");
var temporaryParking = await _context.yuntech_monthly_rent_number
.FirstOrDefaultAsync(x => x.category == "臨停");
if (parkingSpaces != null && monthlyRent != null && temporaryParking != null)
{
// 生成 Excel 文件
var fileBytes = GenerateExcel(parkingSpaces, monthlyRent, temporaryParking);
// 文件名帶上當前時間
var fileName = $"ParkingSpaces_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
var filePath = Path.Combine(_saveDirectory, fileName);
// 保存文件
await File.WriteAllBytesAsync(filePath, fileBytes);
}
}
}
private byte[] GenerateExcel(IEnumerable<Yuntech_parking> parkingData, Yuntech_monthly_rent_number monthlyRent, Yuntech_monthly_rent_number temporaryParking)
{
using var package = new ExcelPackage();
var worksheet = package.Workbook.Worksheets.Add("Yuntech Parking");
// 設定標題
worksheet.Cells[1, 1].Value = "總車位";
worksheet.Cells[1, 2].Value = "剩餘車位";
worksheet.Cells[1, 3].Value = "月租車數量";
worksheet.Cells[1, 4].Value = "臨停數量";
// 添加下載時間
worksheet.Cells[1, 6].Value = "下載時間";
worksheet.Cells[2, 6].Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
var row = 2;
foreach (var item in parkingData)
{
worksheet.Cells[row, 1].Value = item.all_num;
worksheet.Cells[row, 2].Value = item.now_num;
row++;
}
// 添加月租車與臨停車數據
worksheet.Cells[2, 3].Value = monthlyRent.number;
worksheet.Cells[2, 4].Value = temporaryParking.number;
return package.GetAsByteArray();
}
}
}