//using AspNetCore; using ClosedXML.Excel; using DocumentFormat.OpenXml.Spreadsheet; //using DocumentFormat.OpenXml.Spreadsheet; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.Office.Interop.Excel; using Newtonsoft.Json; using System.Diagnostics; using System.Text; using VirtualTask.Models; using X.PagedList; namespace VirtualTask.Controllers { public class RapportiniController : Controller { string apiUrl = string.Empty; string urlBase = string.Empty; string token = string.Empty; string tenant = string.Empty; string errMes = string.Empty; string admin = string.Empty; string time_sheet=string.Empty; HttpClient client; private readonly IConfiguration _configuration; public RapportiniController(IConfiguration configuration) { client = new HttpClient(); _configuration = configuration; var key = _configuration["ApplicationInsights:rootUrlApi"]; apiUrl = key; } #region INDEX public IActionResult Index(string impianto, DateTime dataIni, DateTime dataFin, int? page = 1) { string _log=string.Empty; StringBuilder sb =new StringBuilder(); sb.AppendLine("DATAIN: "+dataIni.ToString()); sb.AppendLine(" DATAFIN: " + dataFin.ToString()); sb.AppendLine(" IMP: " + impianto); _log=sb.ToString(); //ViewBag.Log = _log; SessionHelper helper = new SessionHelper(this); token = helper.GetStringValue("tok"); if (string.IsNullOrEmpty(token)) { return RedirectToAction("Login2", "Login"); } apiUrl = helper.GetStringValue("apiUrl"); admin = helper.GetStringValue("admin"); ViewBag.Admin = admin; time_sheet = helper.GetStringValue("time_sheet"); ViewBag.TimeSheet = time_sheet; urlBase = apiUrl + "rapportiniList"; urlBase = urlBase + "?token=" + token; Uri baseAddress = new Uri(urlBase); client = new HttpClient(); client.BaseAddress = baseAddress; List modelList = new List(); HttpResponseMessage response = client.GetAsync(baseAddress).Result; if (response.IsSuccessStatusCode) { string data = response.Content.ReadAsStringAsync().Result; modelList = JsonConvert.DeserializeObject>(data) ?? new List(); string urlImpianti = apiUrl + "impiantiListMngr?token=" + token; HttpResponseMessage responseImpianti = client.GetAsync(urlImpianti).Result; List impiantiList = new List(); if (responseImpianti.IsSuccessStatusCode) { string dataImpianti = responseImpianti.Content.ReadAsStringAsync().Result; impiantiList = JsonConvert.DeserializeObject>(dataImpianti) ?? new List(); ; //ViewBag.Impianti = impiantiList; // 🔧 Crea SelectList codice + descrizione ViewBag.Impianti = new SelectList( impiantiList.Select(i => new { imcodimp = i.imcodimp, descrizioneCompleta = $"{i.imcodimp} - {i.imdescri}" }), "imcodimp", "descrizioneCompleta", impianto ); } // --- Filtri --- //ViewBag.Rapportini = getImpianti(null); if (!string.IsNullOrEmpty(impianto)) { modelList = modelList.Where(s => s.codice_impianto.Contains(impianto)).ToList(); ViewData["impianto"] = impianto; //ViewBag.Impianto = impianto; } //else // ViewData["impianto"] = null; if (dataIni.Date != DateTime.MinValue) { modelList = modelList.Where(x => x.data_rapportino.GetValueOrDefault().Date >= dataIni.Date).ToList(); ViewData["dataIni"] = dataIni; } else ViewData["dataIni"] = null; if (dataFin.Date != DateTime.MinValue) { modelList = modelList.Where(x => x.data_rapportino.GetValueOrDefault().Date <= dataFin.Date).ToList(); ViewData["dataFin"] = dataFin; } else ViewData["dataFin"] = null; if (page != null && page < 1) { page = 1; } var pageSize = 10; var shortLinks = modelList .OrderByDescending(s => s.seriale_rapportino) .ToPagedList(page ?? 1, pageSize); return View(shortLinks); } else { errMes = response.Content.ReadAsStringAsync().Result; helper.SetStringValue("errMsg", errMes); return RedirectToAction("Error"); } } #endregion INDEX #region metodi interni public IActionResult ExportDataToExcel(DateTime dataIni, DateTime dataFin, string? impianto) { SessionHelper helper = new SessionHelper(this); token = helper.GetStringValue("tok"); if (string.IsNullOrEmpty(token)) { return RedirectToAction("Login2", "Login"); } apiUrl = helper.GetStringValue("apiUrl"); admin = helper.GetStringValue("admin"); ViewBag.Admin = admin; urlBase = apiUrl + "rapportiniList"; urlBase = urlBase + "?token=" + token; Uri baseAddress = new Uri(urlBase); client = new HttpClient(); client.BaseAddress = baseAddress; List modelList = new List(); HttpResponseMessage response = client.GetAsync(baseAddress).Result; if (response.IsSuccessStatusCode) { string data = response.Content.ReadAsStringAsync().Result; modelList = JsonConvert.DeserializeObject>(data); if (impianto != null) { modelList = modelList.Where(x => x.codice_impianto.Equals(impianto)).ToList(); } if (dataIni != DateTime.MinValue) { modelList = modelList .Where(x => x.data_rapportino.GetValueOrDefault().Date >= dataIni.Date) .ToList(); ViewData["dataIni"] = dataIni.ToString("yyyy-MM-dd"); } else { ViewData["dataIni"] = ""; } if (dataFin != DateTime.MinValue) { modelList = modelList .Where(x => x.data_rapportino.GetValueOrDefault().Date <= dataFin.Date) .ToList(); ViewData["dataFin"] = dataFin.ToString("yyyy-MM-dd"); } else { ViewData["dataFin"] = ""; } //if (string.IsNullOrEmpty(impianto)) //{ // impianto = "- Impianto"; //} //if (impianto.Equals("System.Collections.Generic.List`1[Microsoft.AspNetCore.Mvc.Rendering.SelectListItem]") || impianto.Equals("- Impianto")) //{ // modelList = modelList; //} //else //{ // if (impianto != null) // { // modelList = modelList.Where(x => x.codice_impianto.Equals(impianto)).ToList(); // } // if (dataFin != DateTime.MinValue) // { // modelList = modelList.Where(x => x.data_rapportino.GetValueOrDefault().Date >= dataIni.Date // && x.data_rapportino.GetValueOrDefault().Date <= dataFin.Date).ToList(); // } // else // { // modelList = modelList.Where(x => x.data_rapportino.GetValueOrDefault().Date >= dataIni.Date).ToList(); // } //} var workbook = new XLWorkbook(); workbook.AddWorksheet("sheetName"); var ws = workbook.Worksheet("sheetName"); int col = 1; //Scrivo intestazioni colonne foreach (var item in modelList[0].GetType().GetProperties()) { ws.Cell(1, col).Style = ws.Cell(1, col).Style.Font.SetBold(); ws.Cell(1, col).Value = item.Name.ToString().Replace("_", " ").ToUpper(); col++; } var row = 0; foreach (var item in modelList) { var colonna = 1; //righe per ogni item nel modelList foreach (var prop in item.GetType().GetProperties()) { //controllo se item null assegno stringa vuota //perchè se null da errore quando scrive l'excel if (prop.GetValue(item) != null) { ws.Cell(row + 2, colonna).Value = prop.GetValue(item).ToString(); } else { ws.Cell(row + 2, colonna).Value = string.Empty; } colonna++; } row++; } //Salvo il file Excel var anno = DateTime.Now.Year.ToString(); var mese = DateTime.Now.Month.ToString(); var giorno = DateTime.Now.Day.ToString(); var ore = DateTime.Now.Hour.ToString(); var minuti = DateTime.Now.Minute.ToString(); var secondi = DateTime.Now.Second.ToString(); var dateFile = anno + mese + giorno + ore + minuti + secondi; //workbook.SaveAs($"C:\\Users\\utente\\Desktop\\ExcelVT\\buoni_{dateFile}.xlsx"); string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; //string fileName = "authors.xlsx"; string fileName = $"buoni_{dateFile}.xlsx"; using (var stream = new MemoryStream()) { workbook.SaveAs(stream); var content = stream.ToArray(); return File(content, contentType, fileName); } //workbook.SaveAs($"..\\..\\BuoniVT\\buoni_{dateFile}.xlsx"); //workbook.Save(); // return RedirectToAction("Index"); } else { errMes = response.Content.ReadAsStringAsync().Result; helper.SetStringValue("errMsg", errMes); return RedirectToAction("Error"); } } private List getImpianti(string impianto) { SessionHelper helper = new SessionHelper(this); //if (!string.IsNullOrEmpty(impianto)) //{ // helper.SetStringValue("imp", impianto); //} //else //{ // helper.SetStringValue("imp", ""); //} token = helper.GetStringValue("tok"); apiUrl = helper.GetStringValue("apiUrl"); urlBase = apiUrl + "impiantiListMngr"; urlBase = urlBase + "?token=" + token; Uri baseAddress = new Uri(urlBase); client = new HttpClient(); client.BaseAddress = baseAddress; List selectItems = new List(); List modelList = new List(); HttpResponseMessage response = client.GetAsync(baseAddress).Result; if (response.IsSuccessStatusCode) { string data = response.Content.ReadAsStringAsync().Result; modelList = JsonConvert.DeserializeObject>(data); modelList = modelList.Where(x => x.imfinatt == null).ToList(); //per gestire primo elemento tendina (deve essere vuoto) SelectListItem listItemFirt = new SelectListItem(); listItemFirt.Value = string.Empty; listItemFirt.Text = " - Impianto"; selectItems.Add(listItemFirt); foreach (var role in modelList) { SelectListItem listItem = new SelectListItem(); string s = role.imcodimp + " - " + role.imdescri; listItem.Value = role.imcodimp; listItem.Text = s; if (role.imcodimp != null && role.imcodimp.Equals(impianto)) { listItem.Selected = true; } selectItems.Add(listItem); } } return selectItems; } //private List getImpianti() //{ // SessionHelper helper = new SessionHelper(this); // token = helper.GetStringValue("tok"); // apiUrl = helper.GetStringValue("apiUrl"); // urlBase = apiUrl + "rapportiniList"; // urlBase = urlBase + "?token=" + token; // Uri baseAddress = new Uri(urlBase); // client = new HttpClient(); // client.BaseAddress = baseAddress; // List selectItems = new List(); // List modelList = new List(); // HttpResponseMessage response = client.GetAsync(baseAddress).Result; // if (response.IsSuccessStatusCode) // { // string data = response.Content.ReadAsStringAsync().Result; // modelList = JsonConvert.DeserializeObject>(data); // //per gestire primo elemento tendina (deve essere vuoto) // SelectListItem listItemFirt = new SelectListItem(); // listItemFirt.Value = string.Empty; // listItemFirt.Text = " - Impianto"; // selectItems.Add(listItemFirt); // var appoggio = string.Empty; // foreach (var role in modelList) // { // if (!appoggio.Equals(role.codice_impianto)) // { // SelectListItem listItem = new SelectListItem(); // string s = role.codice_impianto; // listItem.Value = role.codice_impianto; // listItem.Text = s; // selectItems.Add(listItem); // } // appoggio = role.codice_impianto; // } // } // return selectItems; //} [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { SessionHelper helper = new SessionHelper(this); string e = helper.GetStringValue("errMsg"); return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, ErrMsg = e }); } #endregion metodi interni } }