using System; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using ClosedXML.Excel; using Microsoft.EntityFrameworkCore; using Parking_space_WebAPI.Models; namespace Parking_space_WebAPI.Services { public class ExcelGenerationService { private readonly SqlContext _context; private readonly string _excelDirectory; public ExcelGenerationService(SqlContext context) { _context = context; _excelDirectory = @"C:\Users\ste92\Desktop\parking-e\excel"; // 設定 Excel 檔案存儲路徑 } public async Task GenerateDailyExcel() { DateTime today = DateTime.Today; // 查詢當天的停車紀錄,按小時分組 var parkingLogs = await _context.ParkingLogs .Where(p => p.Timestamp.Date == today) .GroupBy(p => new { p.Timestamp.Year, p.Timestamp.Month, p.Timestamp.Day, p.Timestamp.Hour }) .Select(g => new { Timestamp = new DateTime(g.Key.Year, g.Key.Month, g.Key.Day, g.Key.Hour, 0, 0), TotalParkingSpaces = g.First().TotalParkingSpaces, // 取每小時第一筆的總車位 RemainingSpaces = g.First().RemainingSpaces, // 取每小時第一筆的剩餘車位 MonthlyRentSpaces = g.First().MonthlyRentSpaces, // 取每小時第一筆的月租車位 TemporaryRentSpaces = g.First().TemporaryRentSpaces // 取每小時第一筆的臨停車位 }) .ToListAsync(); if (parkingLogs.Count == 0) { // 如果當天沒有紀錄,可以選擇不生成檔案或進行其他處理 return; } using (var workbook = new XLWorkbook()) { var worksheet = workbook.Worksheets.Add("當天停車紀錄"); worksheet.Cell(1, 1).Value = "時間"; worksheet.Cell(1, 2).Value = "總車位"; worksheet.Cell(1, 3).Value = "剩餘車位"; worksheet.Cell(1, 4).Value = "月租車位"; worksheet.Cell(1, 5).Value = "臨停車位"; worksheet.Cell(1, 6).Value = "生成日期"; worksheet.Cell(2, 6).Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss dddd"); // 填入當前生成時間 for (int i = 0; i < parkingLogs.Count; i++) { var log = parkingLogs[i]; worksheet.Cell(i + 2, 1).Value = log.Timestamp.ToString("yyyy/MM/dd HH:mm:ss"); worksheet.Cell(i + 2, 2).Value = log.TotalParkingSpaces; worksheet.Cell(i + 2, 3).Value = log.RemainingSpaces; worksheet.Cell(i + 2, 4).Value = log.MonthlyRentSpaces; worksheet.Cell(i + 2, 5).Value = log.TemporaryRentSpaces; } // 設定欄位寬度 worksheet.Column(1).Width = 25; worksheet.Column(2).Width = 15; worksheet.Column(3).Width = 15; worksheet.Column(4).Width = 15; worksheet.Column(5).Width = 15; worksheet.Column(6).Width = 25; // 生成檔案名稱 string fileName = $"整天車位數-{today:yyyy-MM-dd-dddd}.xlsx"; // 儲存檔案 var filePath = Path.Combine(_excelDirectory, fileName); workbook.SaveAs(filePath); } } } }