using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using ClosedXML.Excel; using HRM.BO; namespace HRM.DA { /// /// The LFA payment workbook: builds the template from and reads /// an uploaded one. Only what the file itself can tell is checked here. /// internal static class LFAPaymentWorkbook { #region Template internal static byte[] BuildTemplate() { using (XLWorkbook workbook = new XLWorkbook()) { IXLWorksheet sheet = workbook.Worksheets.Add(LFAPaymentUploadTemplate.SheetName); for (int i = 0; i < LFAPaymentUploadTemplate.Headings.Length; i++) { IXLCell cell = sheet.Cell(LFAPaymentUploadTemplate.HeadingRow, i + 1); cell.Value = LFAPaymentUploadTemplate.Headings[i]; cell.Style.Font.Bold = true; cell.Style.Fill.BackgroundColor = XLColor.FromHtml("#D9E1F2"); cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; cell.Style.Border.OutsideBorder = XLBorderStyleValues.Thin; sheet.Column(i + 1).Width = LFAPaymentUploadTemplate.Widths[i]; } int first = LFAPaymentUploadTemplate.FirstDataRow; int last = first + LFAPaymentUploadTemplate.FormattedDataRows - 1; // Text, so an Employee ID such as 00123 keeps its zeros. sheet.Range(first, LFAPaymentUploadTemplate.EmployeeNoColumn, last, LFAPaymentUploadTemplate.NameColumn) .Style.NumberFormat.Format = "@"; sheet.SheetView.FreezeRows(LFAPaymentUploadTemplate.HeadingRow); using (MemoryStream stream = new MemoryStream()) { workbook.SaveAs(stream); return stream.ToArray(); } } } #endregion #region Read /// The file's rows. Problems go into ; a row with one is not returned. internal static List Read(Stream stream, string fileName, long fileLength, LFAPaymentReadResult result) { List rows = new List(); if (stream == null || string.IsNullOrWhiteSpace(fileName) || fileLength <= 0) { result.AddIssue(0, null, null, "No file was received, or the file is empty."); return rows; } if (!fileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase)) { result.AddIssue(0, null, null, "Only Excel workbooks (.xlsx) are allowed. Please use the downloaded template."); return rows; } if (fileLength > LFAPaymentUploadTemplate.MaxUploadMegabytes * 1024L * 1024L) { result.AddIssue(0, null, null, "The file is larger than " + LFAPaymentUploadTemplate.MaxUploadMegabytes + " MB."); return rows; } // ClosedXML needs a seekable stream; an upload stream may not be one. using (MemoryStream buffer = new MemoryStream()) { stream.CopyTo(buffer); buffer.Position = 0; XLWorkbook workbook; try { workbook = new XLWorkbook(buffer); } catch (Exception) { result.AddIssue(0, null, null, "The file could not be opened as an Excel workbook. It may be damaged or password-protected."); return rows; } using (workbook) { IXLWorksheet sheet; if (!workbook.TryGetWorksheet(LFAPaymentUploadTemplate.SheetName, out sheet)) sheet = workbook.Worksheets.First(); if (!CheckHeadings(sheet, result)) return rows; ReadRows(sheet, rows, result); } } if (rows.Count == 0 && result.Issues.Count == 0) result.AddIssue(0, null, null, "No employee found in the file."); return rows; } private static bool CheckHeadings(IXLWorksheet sheet, LFAPaymentReadResult result) { List wrong = new List(); for (int i = 0; i < LFAPaymentUploadTemplate.Headings.Length; i++) { string found = Text(sheet.Cell(LFAPaymentUploadTemplate.HeadingRow, i + 1)); if (Normalize(found) != Normalize(LFAPaymentUploadTemplate.Headings[i])) wrong.Add("column " + (char)('A' + i) + " must be \"" + LFAPaymentUploadTemplate.Headings[i] + "\"" + (found == "" ? " (it is empty)" : " (found \"" + found + "\")")); } if (wrong.Count == 0) return true; result.AddIssue(0, null, null, "The headings in row " + LFAPaymentUploadTemplate.HeadingRow + " do not match the template: " + string.Join(", ", wrong) + "."); return false; } private static void ReadRows(IXLWorksheet sheet, List rows, LFAPaymentReadResult result) { // cells with a value only: the template's formatted but empty rows are not "used" int lastRow = sheet.LastRowUsed(XLCellsUsedOptions.Contents)?.RowNumber() ?? 0; int count = 0; for (int rowNo = LFAPaymentUploadTemplate.FirstDataRow; rowNo <= lastRow; rowNo++) { string employeeNo = Text(sheet.Cell(rowNo, LFAPaymentUploadTemplate.EmployeeNoColumn)); string name = Text(sheet.Cell(rowNo, LFAPaymentUploadTemplate.NameColumn)); if (employeeNo == "" && name == "") continue; if (++count > LFAPaymentUploadTemplate.MaxRows) { rows.Clear(); result.AddIssue(0, null, null, "The file has more than " + LFAPaymentUploadTemplate.MaxRows + " employees. Please split it."); return; } if (employeeNo == "") { result.AddIssue(rowNo, null, name, "Employee ID is required."); continue; } rows.Add(new LFAPaymentInput { RowNo = rowNo, EmployeeNo = employeeNo }); } } /// What the cell holds, as text; an Employee ID stored as a number comes without separators. private static string Text(IXLCell cell) { if (cell.DataType == XLDataType.Number) { string shown = cell.GetFormattedString().Trim(); return shown.Length > 0 && shown.All(char.IsDigit) ? shown : cell.GetDouble().ToString("0.##########", CultureInfo.InvariantCulture); } return cell.GetFormattedString().Trim(); } private static string Normalize(string heading) { return new string((heading ?? "").Where(x => !char.IsWhiteSpace(x)).ToArray()).ToUpperInvariant(); } #endregion } }