| | | 1 | | using OfficeOpenXml; |
| | | 2 | | using OzonDomains.Models.MatchedRowSys; |
| | | 3 | | using Services.ParserServices.FielParsers.Models; |
| | | 4 | | using Services.ReleasServices.ReleaseManager; |
| | | 5 | | using System.Globalization; |
| | | 6 | | using System.Text; |
| | | 7 | | using System.Text.RegularExpressions; |
| | | 8 | | using NPOI.SS.UserModel; |
| | | 9 | | using NPOI.HSSF.UserModel; |
| | | 10 | | |
| | | 11 | | namespace Services.ParserServices.FielParsers |
| | | 12 | | { |
| | | 13 | | public class ExcelParser |
| | | 14 | | { |
| | | 15 | | private readonly ReleaseManager _releaseManager; |
| | | 16 | | private CultureInfo _culture; |
| | | 17 | | |
| | 0 | 18 | | public ExcelParser(ReleaseManager releaseManager) |
| | | 19 | | { |
| | 0 | 20 | | _releaseManager = releaseManager; |
| | 0 | 21 | | _culture = _releaseManager.GetCultureInfo(); |
| | 0 | 22 | | ExcelPackage.LicenseContext = LicenseContext.NonCommercial; |
| | 0 | 23 | | } |
| | | 24 | | |
| | | 25 | | public List<Dictionary<string, string>> UpdateTableToStandartColumns(List<Dictionary<string, string>> table, |
| | | 26 | | Dictionary<string, string> columnMappings) |
| | | 27 | | { |
| | 0 | 28 | | var updatedTableData = new List<Dictionary<string, string>>(); |
| | | 29 | | |
| | | 30 | | // Определяем служебные столбцы, которые нужно сохранить как есть |
| | 0 | 31 | | var preservedColumns = new HashSet<string> { "Целая часть", "Дробная часть" }; |
| | | 32 | | |
| | | 33 | | // Создаем нормализованный словарь для быстрого поиска |
| | | 34 | | // Нормализуем значения из columnMappings для сравнения |
| | 0 | 35 | | var normalizedMappings = new Dictionary<string, (string OriginalKey, string OriginalValue)>(); |
| | 0 | 36 | | foreach (var mapping in columnMappings) |
| | | 37 | | { |
| | 0 | 38 | | if (!string.IsNullOrEmpty(mapping.Value)) |
| | | 39 | | { |
| | 0 | 40 | | var normalizedValue = NormalizeHeaderName(mapping.Value); |
| | | 41 | | // Если уже есть такой нормализованный ключ, используем первый найденный |
| | 0 | 42 | | if (!normalizedMappings.ContainsKey(normalizedValue)) |
| | | 43 | | { |
| | 0 | 44 | | normalizedMappings[normalizedValue] = (mapping.Key, mapping.Value); |
| | | 45 | | } |
| | | 46 | | } |
| | | 47 | | } |
| | | 48 | | |
| | 0 | 49 | | foreach (var row in table) |
| | | 50 | | { |
| | 0 | 51 | | var updatedRow = new Dictionary<string, string>(); |
| | | 52 | | |
| | 0 | 53 | | foreach (var column in row) |
| | | 54 | | { |
| | | 55 | | // Если столбец нужно сохранить как есть |
| | 0 | 56 | | if (preservedColumns.Contains(column.Key)) |
| | | 57 | | { |
| | 0 | 58 | | updatedRow.Add(column.Key, column.Value); |
| | 0 | 59 | | continue; |
| | | 60 | | } |
| | | 61 | | |
| | | 62 | | // Нормализуем имя столбца для сравнения |
| | 0 | 63 | | var normalizedColumnKey = NormalizeHeaderName(column.Key); |
| | | 64 | | |
| | | 65 | | // Ищем сопоставление по нормализованному значению |
| | 0 | 66 | | if (normalizedMappings.TryGetValue(normalizedColumnKey, out var mapping)) |
| | | 67 | | { |
| | 0 | 68 | | updatedRow.Add(mapping.OriginalKey, column.Value); |
| | | 69 | | } |
| | | 70 | | } |
| | | 71 | | |
| | 0 | 72 | | updatedTableData.Add(updatedRow); |
| | | 73 | | } |
| | | 74 | | |
| | 0 | 75 | | return updatedTableData; |
| | | 76 | | } |
| | | 77 | | |
| | | 78 | | /// <summary> |
| | | 79 | | /// Нормализует имя заголовка для сравнения: убирает лишние пробелы, нормализует переносы строк |
| | | 80 | | /// </summary> |
| | | 81 | | private string NormalizeHeaderName(string headerName) |
| | | 82 | | { |
| | 0 | 83 | | if (string.IsNullOrEmpty(headerName)) |
| | 0 | 84 | | return string.Empty; |
| | | 85 | | |
| | | 86 | | // Заменяем различные варианты переносов строк на пробелы |
| | 0 | 87 | | var normalized = headerName |
| | 0 | 88 | | .Replace("\r\n", " ") // Windows line break |
| | 0 | 89 | | .Replace("\n", " ") // Unix line break |
| | 0 | 90 | | .Replace("\r", " ") // Old Mac line break |
| | 0 | 91 | | .Replace("\t", " ") // Tabs |
| | 0 | 92 | | .Replace("\u00A0", " ") // Non-breaking space |
| | 0 | 93 | | .Replace("\u2009", " ") // Thin space |
| | 0 | 94 | | .Replace("\u200A", " ") // Hair space |
| | 0 | 95 | | .Replace("\u202F", " ") // Narrow no-break space |
| | 0 | 96 | | .Replace("\u205F", " "); // Medium mathematical space |
| | | 97 | | |
| | | 98 | | // Убираем множественные пробелы и обрезаем |
| | 0 | 99 | | normalized = Regex.Replace(normalized, @"\s+", " ").Trim(); |
| | | 100 | | |
| | 0 | 101 | | return normalized; |
| | | 102 | | } |
| | | 103 | | |
| | | 104 | | public MemoryStream ConvertCsvToExcel(Stream csvStream, char delimiter) |
| | | 105 | | { |
| | 0 | 106 | | csvStream.Position = 0; |
| | | 107 | | |
| | 0 | 108 | | var excelStream = new MemoryStream(); |
| | | 109 | | |
| | 0 | 110 | | using (var package = new ExcelPackage()) |
| | | 111 | | { |
| | 0 | 112 | | var worksheet = package.Workbook.Worksheets.Add("Sheet1"); |
| | | 113 | | |
| | 0 | 114 | | using (var reader = new StreamReader(csvStream, Encoding.UTF8)) |
| | | 115 | | { |
| | 0 | 116 | | int row = 1; |
| | 0 | 117 | | while (!reader.EndOfStream) |
| | | 118 | | { |
| | 0 | 119 | | string? line = reader.ReadLine(); |
| | 0 | 120 | | if (line == null) |
| | 0 | 121 | | break; |
| | 0 | 122 | | string[] cells = SplitCsvLine(line, delimiter); |
| | | 123 | | |
| | 0 | 124 | | for (int col = 0; col < cells.Length; col++) |
| | | 125 | | { |
| | 0 | 126 | | worksheet.Cells[row, col + 1].Value = cells[col]; |
| | | 127 | | } |
| | | 128 | | |
| | 0 | 129 | | row++; |
| | | 130 | | } |
| | 0 | 131 | | } |
| | | 132 | | |
| | 0 | 133 | | package.SaveAs(excelStream); |
| | 0 | 134 | | } |
| | | 135 | | |
| | 0 | 136 | | excelStream.Position = 0; |
| | 0 | 137 | | return excelStream; |
| | | 138 | | } |
| | | 139 | | |
| | | 140 | | private string[] SplitCsvLine(string line, char delimiter) |
| | | 141 | | { |
| | 0 | 142 | | List<string> cells = new List<string>(); |
| | | 143 | | |
| | 0 | 144 | | bool inQuotes = false; |
| | 0 | 145 | | StringBuilder currentCell = new StringBuilder(); |
| | | 146 | | |
| | 0 | 147 | | for (int i = 0; i < line.Length; i++) |
| | | 148 | | { |
| | 0 | 149 | | char c = line[i]; |
| | | 150 | | |
| | 0 | 151 | | if (c == '"') |
| | | 152 | | { |
| | 0 | 153 | | inQuotes = !inQuotes; |
| | | 154 | | } |
| | 0 | 155 | | else if (c == delimiter && !inQuotes) |
| | | 156 | | { |
| | 0 | 157 | | cells.Add(currentCell.ToString().Trim('"')); |
| | 0 | 158 | | currentCell.Clear(); |
| | | 159 | | } |
| | | 160 | | else |
| | | 161 | | { |
| | 0 | 162 | | currentCell.Append(c); |
| | | 163 | | } |
| | | 164 | | } |
| | | 165 | | |
| | 0 | 166 | | cells.Add(currentCell.ToString().Trim('"')); |
| | 0 | 167 | | return cells.ToArray(); |
| | | 168 | | } |
| | | 169 | | |
| | | 170 | | |
| | | 171 | | /// <summary> |
| | | 172 | | /// Определяет формат Excel файла по потоку |
| | | 173 | | /// </summary> |
| | | 174 | | private bool IsXlsFormat(Stream stream) |
| | | 175 | | { |
| | 0 | 176 | | if (!stream.CanSeek) |
| | 0 | 177 | | return false; |
| | | 178 | | |
| | 0 | 179 | | var position = stream.Position; |
| | | 180 | | try |
| | | 181 | | { |
| | 0 | 182 | | stream.Seek(0, SeekOrigin.Begin); |
| | 0 | 183 | | var header = new byte[8]; |
| | 0 | 184 | | stream.Read(header, 0, 8); |
| | 0 | 185 | | stream.Seek(position, SeekOrigin.Begin); |
| | | 186 | | |
| | | 187 | | // .xls файлы начинаются с определенной сигнатурой |
| | | 188 | | // OLE2 файлы начинаются с 0xD0CF11E0A1B11AE1 |
| | 0 | 189 | | return header[0] == 0xD0 && header[1] == 0xCF && header[2] == 0x11 && header[3] == 0xE0; |
| | | 190 | | } |
| | 0 | 191 | | catch |
| | | 192 | | { |
| | 0 | 193 | | stream.Seek(position, SeekOrigin.Begin); |
| | 0 | 194 | | return false; |
| | | 195 | | } |
| | 0 | 196 | | } |
| | | 197 | | |
| | | 198 | | /// <summary> |
| | | 199 | | /// Получает значение ячейки из NPOI |
| | | 200 | | /// </summary> |
| | | 201 | | private string GetCellValueFromNpoi(ICell cell) |
| | | 202 | | { |
| | 0 | 203 | | if (cell == null) |
| | 0 | 204 | | return string.Empty; |
| | | 205 | | |
| | 0 | 206 | | switch (cell.CellType) |
| | | 207 | | { |
| | | 208 | | case CellType.Numeric: |
| | 0 | 209 | | if (DateUtil.IsCellDateFormatted(cell)) |
| | | 210 | | { |
| | 0 | 211 | | return (cell.DateCellValue ?? DateTime.MinValue) |
| | 0 | 212 | | .ToString("dd.MM.yyyy", CultureInfo.InvariantCulture); |
| | | 213 | | } |
| | | 214 | | |
| | 0 | 215 | | return cell.NumericCellValue.ToString(_culture); |
| | | 216 | | case CellType.String: |
| | 0 | 217 | | return cell.StringCellValue; |
| | | 218 | | case CellType.Boolean: |
| | 0 | 219 | | return cell.BooleanCellValue.ToString(); |
| | | 220 | | case CellType.Formula: |
| | | 221 | | try |
| | | 222 | | { |
| | 0 | 223 | | if (cell.CachedFormulaResultType == CellType.String) |
| | 0 | 224 | | return cell.StringCellValue; |
| | 0 | 225 | | else if (cell.CachedFormulaResultType == CellType.Numeric) |
| | 0 | 226 | | return cell.NumericCellValue.ToString(_culture); |
| | 0 | 227 | | else if (cell.CachedFormulaResultType == CellType.Boolean) |
| | 0 | 228 | | return cell.BooleanCellValue.ToString(); |
| | | 229 | | else |
| | 0 | 230 | | return cell.StringCellValue; |
| | | 231 | | } |
| | 0 | 232 | | catch |
| | | 233 | | { |
| | 0 | 234 | | return cell.NumericCellValue.ToString(_culture); |
| | | 235 | | } |
| | | 236 | | default: |
| | 0 | 237 | | return string.Empty; |
| | | 238 | | } |
| | 0 | 239 | | } |
| | | 240 | | |
| | | 241 | | public async Task<List<string>> GetTableHeadersAsync(Stream excelStream, int startRow = 1, int startColumn = 1) |
| | | 242 | | { |
| | 0 | 243 | | return await Task.Run(() => |
| | 0 | 244 | | { |
| | 0 | 245 | | // Создаем копию потока для чтения, чтобы избежать проблем с позицией |
| | 0 | 246 | | using (var streamCopy = new MemoryStream()) |
| | 0 | 247 | | { |
| | 0 | 248 | | if (excelStream.CanSeek) |
| | 0 | 249 | | { |
| | 0 | 250 | | excelStream.Seek(0, SeekOrigin.Begin); |
| | 0 | 251 | | } |
| | 0 | 252 | | excelStream.CopyTo(streamCopy); |
| | 0 | 253 | | streamCopy.Position = 0; |
| | 0 | 254 | | |
| | 0 | 255 | | // Проверяем формат файла |
| | 0 | 256 | | if (IsXlsFormat(streamCopy)) |
| | 0 | 257 | | { |
| | 0 | 258 | | return GetTableHeadersFromXls(streamCopy, startRow, startColumn); |
| | 0 | 259 | | } |
| | 0 | 260 | | else |
| | 0 | 261 | | { |
| | 0 | 262 | | return GetTableHeadersFromXlsx(streamCopy, startRow, startColumn); |
| | 0 | 263 | | } |
| | 0 | 264 | | } |
| | 0 | 265 | | }); |
| | 0 | 266 | | } |
| | | 267 | | |
| | | 268 | | private List<string> GetTableHeadersFromXls(Stream excelStream, int startRow, int startColumn) |
| | | 269 | | { |
| | 0 | 270 | | var headers = new List<string>(); |
| | | 271 | | |
| | 0 | 272 | | if (excelStream.CanSeek) |
| | | 273 | | { |
| | 0 | 274 | | excelStream.Seek(0, SeekOrigin.Begin); |
| | | 275 | | } |
| | | 276 | | |
| | 0 | 277 | | using (var workbook = new HSSFWorkbook(excelStream, true)) |
| | | 278 | | { |
| | 0 | 279 | | var worksheet = workbook.GetSheetAt(0); |
| | 0 | 280 | | var headerRow = worksheet.GetRow(startRow - 1); // NPOI использует 0-based индексы |
| | | 281 | | |
| | 0 | 282 | | if (headerRow != null) |
| | | 283 | | { |
| | 0 | 284 | | for (int col = startColumn - 1; col < headerRow.LastCellNum; col++) |
| | | 285 | | { |
| | 0 | 286 | | var cell = headerRow.GetCell(col); |
| | 0 | 287 | | headers.Add(GetCellValueFromNpoi(cell)); |
| | | 288 | | } |
| | | 289 | | } |
| | 0 | 290 | | } |
| | | 291 | | |
| | 0 | 292 | | return headers; |
| | | 293 | | } |
| | | 294 | | |
| | | 295 | | private List<string> GetTableHeadersFromXlsx(Stream excelStream, int startRow, int startColumn) |
| | | 296 | | { |
| | 0 | 297 | | var headers = new List<string>(); |
| | | 298 | | |
| | 0 | 299 | | using (var package = new ExcelPackage(excelStream)) |
| | | 300 | | { |
| | 0 | 301 | | var worksheet = package.Workbook.Worksheets[0]; |
| | | 302 | | |
| | 0 | 303 | | foreach (var cell in worksheet.Cells[startRow, startColumn, startRow, |
| | 0 | 304 | | worksheet.Dimension.End.Column]) |
| | | 305 | | { |
| | 0 | 306 | | headers.Add(cell.Text); |
| | | 307 | | } |
| | | 308 | | } |
| | | 309 | | |
| | 0 | 310 | | return headers; |
| | | 311 | | } |
| | | 312 | | |
| | | 313 | | public async Task<List<Dictionary<string, string>>> GetTableDataAsync(Stream excelStream, int startRow = 1, |
| | | 314 | | int startColumn = 1) |
| | | 315 | | { |
| | 0 | 316 | | return await Task.Run(() => |
| | 0 | 317 | | { |
| | 0 | 318 | | // Создаем копию потока для чтения, чтобы избежать проблем с позицией |
| | 0 | 319 | | using (var streamCopy = new MemoryStream()) |
| | 0 | 320 | | { |
| | 0 | 321 | | if (excelStream.CanSeek) |
| | 0 | 322 | | { |
| | 0 | 323 | | excelStream.Seek(0, SeekOrigin.Begin); |
| | 0 | 324 | | } |
| | 0 | 325 | | excelStream.CopyTo(streamCopy); |
| | 0 | 326 | | streamCopy.Position = 0; |
| | 0 | 327 | | |
| | 0 | 328 | | // Проверяем формат файла |
| | 0 | 329 | | if (IsXlsFormat(streamCopy)) |
| | 0 | 330 | | { |
| | 0 | 331 | | return GetTableDataFromXls(streamCopy, startRow, startColumn); |
| | 0 | 332 | | } |
| | 0 | 333 | | else |
| | 0 | 334 | | { |
| | 0 | 335 | | return GetTableDataFromXlsx(streamCopy, startRow, startColumn); |
| | 0 | 336 | | } |
| | 0 | 337 | | } |
| | 0 | 338 | | }); |
| | 0 | 339 | | } |
| | | 340 | | |
| | | 341 | | private List<Dictionary<string, string>> GetTableDataFromXls(Stream excelStream, int startRow, int startColumn) |
| | | 342 | | { |
| | 0 | 343 | | var tableData = new List<Dictionary<string, string>>(); |
| | | 344 | | |
| | 0 | 345 | | if (excelStream.CanSeek) |
| | | 346 | | { |
| | 0 | 347 | | excelStream.Seek(0, SeekOrigin.Begin); |
| | | 348 | | } |
| | | 349 | | |
| | 0 | 350 | | using (var workbook = new HSSFWorkbook(excelStream, true)) |
| | | 351 | | { |
| | 0 | 352 | | var worksheet = workbook.GetSheetAt(0); |
| | 0 | 353 | | var headers = new List<string>(); |
| | | 354 | | |
| | | 355 | | // Получаем заголовки |
| | 0 | 356 | | var headerRow = worksheet.GetRow(startRow - 1); |
| | 0 | 357 | | if (headerRow != null) |
| | | 358 | | { |
| | 0 | 359 | | for (int col = startColumn - 1; col < headerRow.LastCellNum; col++) |
| | | 360 | | { |
| | 0 | 361 | | var cell = headerRow.GetCell(col); |
| | 0 | 362 | | headers.Add(GetCellValueFromNpoi(cell)); |
| | | 363 | | } |
| | | 364 | | } |
| | | 365 | | |
| | | 366 | | // Получаем данные |
| | 0 | 367 | | for (int rowIndex = startRow; rowIndex <= worksheet.LastRowNum; rowIndex++) |
| | | 368 | | { |
| | 0 | 369 | | var row = worksheet.GetRow(rowIndex); |
| | 0 | 370 | | if (row == null) continue; |
| | | 371 | | |
| | 0 | 372 | | var rowData = new Dictionary<string, string>(); |
| | 0 | 373 | | bool rowIsEmpty = true; |
| | | 374 | | |
| | 0 | 375 | | for (int col = startColumn - 1; col < row.LastCellNum; col++) |
| | | 376 | | { |
| | 0 | 377 | | var cell = row.GetCell(col); |
| | 0 | 378 | | string cellText = GetCellValueFromNpoi(cell); |
| | | 379 | | |
| | 0 | 380 | | if (!string.IsNullOrWhiteSpace(cellText)) |
| | | 381 | | { |
| | 0 | 382 | | rowIsEmpty = false; |
| | | 383 | | } |
| | | 384 | | |
| | 0 | 385 | | int headerIndex = col - (startColumn - 1); |
| | 0 | 386 | | if (headerIndex < headers.Count && !string.IsNullOrWhiteSpace(headers[headerIndex])) |
| | | 387 | | { |
| | 0 | 388 | | rowData[headers[headerIndex]] = cellText; |
| | | 389 | | } |
| | | 390 | | } |
| | | 391 | | |
| | 0 | 392 | | if (!rowIsEmpty) |
| | | 393 | | { |
| | 0 | 394 | | tableData.Add(rowData); |
| | | 395 | | } |
| | | 396 | | } |
| | 0 | 397 | | } |
| | | 398 | | |
| | 0 | 399 | | return tableData; |
| | | 400 | | } |
| | | 401 | | |
| | | 402 | | private List<Dictionary<string, string>> GetTableDataFromXlsx(Stream excelStream, int startRow, int startColumn) |
| | | 403 | | { |
| | 0 | 404 | | var tableData = new List<Dictionary<string, string>>(); |
| | | 405 | | |
| | 0 | 406 | | using (var package = new ExcelPackage(excelStream)) |
| | | 407 | | { |
| | 0 | 408 | | var worksheet = package.Workbook.Worksheets[0]; |
| | 0 | 409 | | var headers = new List<string>(); |
| | | 410 | | |
| | 0 | 411 | | foreach (var cell in worksheet.Cells[startRow, startColumn, startRow, |
| | 0 | 412 | | worksheet.Dimension.End.Column]) |
| | | 413 | | { |
| | 0 | 414 | | headers.Add(cell.Text); |
| | | 415 | | } |
| | | 416 | | |
| | 0 | 417 | | for (int row = startRow + 1; row <= worksheet.Dimension.End.Row; row++) |
| | | 418 | | { |
| | 0 | 419 | | var rowData = new Dictionary<string, string>(); |
| | 0 | 420 | | bool rowIsEmpty = true; |
| | | 421 | | |
| | 0 | 422 | | for (int col = startColumn; col <= worksheet.Dimension.End.Column; col++) |
| | | 423 | | { |
| | 0 | 424 | | var cell = worksheet.Cells[row, col]; |
| | | 425 | | string cellText; |
| | | 426 | | |
| | 0 | 427 | | if (cell.Value is DateTime dateValue) |
| | | 428 | | { |
| | 0 | 429 | | cellText = dateValue.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture); |
| | | 430 | | } |
| | | 431 | | else |
| | | 432 | | { |
| | 0 | 433 | | cellText = cell.Text; |
| | | 434 | | } |
| | | 435 | | |
| | 0 | 436 | | if (!string.IsNullOrWhiteSpace(cellText)) |
| | | 437 | | { |
| | 0 | 438 | | rowIsEmpty = false; |
| | | 439 | | } |
| | | 440 | | |
| | 0 | 441 | | if (col - startColumn < headers.Count && |
| | 0 | 442 | | !string.IsNullOrWhiteSpace(headers[col - startColumn])) |
| | | 443 | | { |
| | 0 | 444 | | rowData[headers[col - startColumn]] = cellText; |
| | | 445 | | } |
| | | 446 | | } |
| | | 447 | | |
| | 0 | 448 | | if (!rowIsEmpty) |
| | | 449 | | { |
| | 0 | 450 | | tableData.Add(rowData); |
| | | 451 | | } |
| | | 452 | | } |
| | 0 | 453 | | } |
| | | 454 | | |
| | 0 | 455 | | return tableData; |
| | | 456 | | } |
| | | 457 | | |
| | | 458 | | public async Task<List<Dictionary<string, string>>> GetTableDataAsyncForDropbox(Stream excelStream, |
| | | 459 | | int startRow = 1, int startColumn = 1) |
| | | 460 | | { |
| | 0 | 461 | | return await Task.Run(() => |
| | 0 | 462 | | { |
| | 0 | 463 | | var tableData = new List<Dictionary<string, string>>(); |
| | 0 | 464 | | |
| | 0 | 465 | | using (var package = new ExcelPackage(excelStream)) |
| | 0 | 466 | | { |
| | 0 | 467 | | var worksheet = package.Workbook.Worksheets[0]; |
| | 0 | 468 | | var headers = new List<string>(); |
| | 0 | 469 | | |
| | 0 | 470 | | // Собираем заголовки |
| | 0 | 471 | | foreach (var cell in worksheet.Cells[startRow, startColumn, startRow, |
| | 0 | 472 | | worksheet.Dimension.End.Column]) |
| | 0 | 473 | | { |
| | 0 | 474 | | headers.Add(cell.Text); |
| | 0 | 475 | | } |
| | 0 | 476 | | |
| | 0 | 477 | | // Добавляем новые заголовки для частей цены |
| | 0 | 478 | | var extendedHeaders = new List<string>(headers); |
| | 0 | 479 | | extendedHeaders.Add("Целая часть"); |
| | 0 | 480 | | extendedHeaders.Add("Дробная часть"); |
| | 0 | 481 | | |
| | 0 | 482 | | for (int row = startRow + 1; row <= worksheet.Dimension.End.Row; row++) |
| | 0 | 483 | | { |
| | 0 | 484 | | var rowData = new Dictionary<string, string>(); |
| | 0 | 485 | | bool rowIsEmpty = true; |
| | 0 | 486 | | |
| | 0 | 487 | | for (int col = startColumn; col <= worksheet.Dimension.End.Column; col++) |
| | 0 | 488 | | { |
| | 0 | 489 | | var cell = worksheet.Cells[row, col]; |
| | 0 | 490 | | string cellText; |
| | 0 | 491 | | string[] formats = { "dd/MM/yyyy", "MM/dd/yyyy", "yyyy-MM-dd" }; |
| | 0 | 492 | | CultureInfo provider = CultureInfo.InvariantCulture; |
| | 0 | 493 | | |
| | 0 | 494 | | string? rawText = cell.Text?.Trim(); |
| | 0 | 495 | | if (rawText != null && |
| | 0 | 496 | | (col - startColumn) < headers.Count && |
| | 0 | 497 | | string.Equals(headers[col - startColumn]?.Trim(), "Цена", |
| | 0 | 498 | | StringComparison.OrdinalIgnoreCase)) |
| | 0 | 499 | | { |
| | 0 | 500 | | string normalizedText = rawText.Replace(" ", "").Replace("'", ""); |
| | 0 | 501 | | string[] parts; |
| | 0 | 502 | | |
| | 0 | 503 | | if (normalizedText.Contains(',')) |
| | 0 | 504 | | { |
| | 0 | 505 | | parts = normalizedText.Split(','); |
| | 0 | 506 | | } |
| | 0 | 507 | | else if (normalizedText.Contains('.')) |
| | 0 | 508 | | { |
| | 0 | 509 | | parts = normalizedText.Split('.'); |
| | 0 | 510 | | } |
| | 0 | 511 | | else |
| | 0 | 512 | | { |
| | 0 | 513 | | parts = new string[] { normalizedText }; |
| | 0 | 514 | | } |
| | 0 | 515 | | |
| | 0 | 516 | | if (parts.Length == 2) |
| | 0 | 517 | | { |
| | 0 | 518 | | rowData["Целая часть"] = parts[0]; |
| | 0 | 519 | | rowData["Дробная часть"] = parts[1]; |
| | 0 | 520 | | cellText = normalizedText; |
| | 0 | 521 | | Console.WriteLine($"Разделено: целая='{parts[0]}', дробная='{parts[1]}'"); |
| | 0 | 522 | | } |
| | 0 | 523 | | else if (parts.Length == 1) |
| | 0 | 524 | | { |
| | 0 | 525 | | rowData["Целая часть"] = parts[0]; |
| | 0 | 526 | | rowData["Дробная часть"] = "0"; // или string.Empty |
| | 0 | 527 | | cellText = normalizedText; |
| | 0 | 528 | | Console.WriteLine($"Только целая часть: '{parts[0]}'"); |
| | 0 | 529 | | } |
| | 0 | 530 | | else |
| | 0 | 531 | | { |
| | 0 | 532 | | cellText = rawText; |
| | 0 | 533 | | rowData["Целая часть"] = string.Empty; |
| | 0 | 534 | | rowData["Дробная часть"] = string.Empty; |
| | 0 | 535 | | Console.WriteLine($"Некорректный формат цены: '{rawText}'"); |
| | 0 | 536 | | } |
| | 0 | 537 | | } |
| | 0 | 538 | | else if (rawText != null && DateTime.TryParseExact(rawText, formats, provider, DateTimeStyle |
| | 0 | 539 | | out DateTime dateValue)) |
| | 0 | 540 | | { |
| | 0 | 541 | | cellText = dateValue.ToString("dd.MM.yyyy", new CultureInfo("ru-RU")); |
| | 0 | 542 | | } |
| | 0 | 543 | | else |
| | 0 | 544 | | { |
| | 0 | 545 | | cellText = rawText ?? string.Empty; |
| | 0 | 546 | | } |
| | 0 | 547 | | |
| | 0 | 548 | | if (!string.IsNullOrWhiteSpace(cellText)) |
| | 0 | 549 | | { |
| | 0 | 550 | | rowIsEmpty = false; |
| | 0 | 551 | | } |
| | 0 | 552 | | |
| | 0 | 553 | | if (col - startColumn < headers.Count && |
| | 0 | 554 | | !string.IsNullOrWhiteSpace(headers[col - startColumn])) |
| | 0 | 555 | | { |
| | 0 | 556 | | rowData[headers[col - startColumn]!] = cellText; |
| | 0 | 557 | | } |
| | 0 | 558 | | } |
| | 0 | 559 | | |
| | 0 | 560 | | if (!rowIsEmpty) |
| | 0 | 561 | | { |
| | 0 | 562 | | tableData.Add(rowData); |
| | 0 | 563 | | } |
| | 0 | 564 | | } |
| | 0 | 565 | | } |
| | 0 | 566 | | |
| | 0 | 567 | | return tableData; |
| | 0 | 568 | | }); |
| | 0 | 569 | | } |
| | | 570 | | |
| | | 571 | | public static bool IsNumeric(object Expression) |
| | | 572 | | { |
| | | 573 | | double retNum; |
| | | 574 | | |
| | 0 | 575 | | bool isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, |
| | 0 | 576 | | System.Globalization.NumberFormatInfo.InvariantInfo, out retNum); |
| | 0 | 577 | | return isNum; |
| | | 578 | | } |
| | | 579 | | |
| | | 580 | | public async Task<List<MatchedRowModel>> MatchExcelDataAsync(Stream file1Stream, |
| | | 581 | | Stream file2Stream, |
| | | 582 | | List<MatchingColumn> matchingColumns, |
| | | 583 | | int startRow1, |
| | | 584 | | int startColumn1, |
| | | 585 | | int startRow2, |
| | | 586 | | int startColumn2) |
| | | 587 | | { |
| | 0 | 588 | | var matchedRows = new List<MatchedRowModel>(); |
| | | 589 | | |
| | 0 | 590 | | var headersFile1 = await GetTableHeadersAsync(file1Stream, startRow1, startColumn1); |
| | 0 | 591 | | file1Stream.Position = 0; |
| | 0 | 592 | | var dataFile1 = await GetTableDataAsync(file1Stream, startRow1, startColumn1); |
| | | 593 | | |
| | 0 | 594 | | var headersFile2 = await GetTableHeadersAsync(file2Stream, startRow2, startColumn2); |
| | 0 | 595 | | file2Stream.Position = 0; |
| | 0 | 596 | | var dataFile2 = await GetTableDataAsync(file2Stream, startRow2, startColumn2); |
| | | 597 | | |
| | 0 | 598 | | headersFile1 = headersFile1.Distinct().ToList(); |
| | 0 | 599 | | headersFile2 = headersFile2.Distinct().ToList(); |
| | | 600 | | |
| | 0 | 601 | | var unmatchedRowsFromFile2 = new List<Dictionary<string, string>>(); |
| | | 602 | | |
| | 0 | 603 | | foreach (var rowFile1 in dataFile1) |
| | | 604 | | { |
| | 0 | 605 | | var matchedRow = new MatchedRowModel |
| | 0 | 606 | | { |
| | 0 | 607 | | File1Data = rowFile1, |
| | 0 | 608 | | File2Data = null |
| | 0 | 609 | | }; |
| | | 610 | | |
| | 0 | 611 | | var rowsToRemove = new List<Dictionary<string, string>>(); |
| | 0 | 612 | | foreach (var rowFile2 in dataFile2) |
| | | 613 | | { |
| | 0 | 614 | | bool isMatch = matchingColumns.All(match => |
| | 0 | 615 | | { |
| | 0 | 616 | | var match1 = match.Item1?.ToLower().Trim(); |
| | 0 | 617 | | var match2 = match.Item2?.ToLower().Trim(); |
| | 0 | 618 | | if (string.IsNullOrEmpty(match1) || string.IsNullOrEmpty(match2) || |
| | 0 | 619 | | !rowFile1.Any(e => e.Key.ToLower().Trim() == match1) || |
| | 0 | 620 | | !rowFile2.Any(e => e.Key.ToLower().Trim() == match2)) |
| | 0 | 621 | | { |
| | 0 | 622 | | return false; |
| | 0 | 623 | | } |
| | 0 | 624 | | |
| | 0 | 625 | | var rowFile1List = rowFile1.ToList(); |
| | 0 | 626 | | var rowFile2List = rowFile2.ToList(); |
| | 0 | 627 | | |
| | 0 | 628 | | var index1 = rowFile1List.FindIndex(e => e.Key.ToLower().Trim() == match1); |
| | 0 | 629 | | var index2 = rowFile2List.FindIndex(e => e.Key.ToLower().Trim() == match2); |
| | 0 | 630 | | |
| | 0 | 631 | | if (index1 != -1 && index2 != -1) |
| | 0 | 632 | | { |
| | 0 | 633 | | var value1 = rowFile1List[index1].Value; |
| | 0 | 634 | | var value2 = rowFile2List[index2].Value; |
| | 0 | 635 | | return CompareValues(value1, value2); |
| | 0 | 636 | | } |
| | 0 | 637 | | |
| | 0 | 638 | | return false; |
| | 0 | 639 | | }); |
| | | 640 | | |
| | 0 | 641 | | if (isMatch) |
| | | 642 | | { |
| | 0 | 643 | | if (matchedRow.File2Data == null) |
| | | 644 | | { |
| | 0 | 645 | | matchedRow.File2Data = new List<Dictionary<string, string>>(); |
| | | 646 | | } |
| | | 647 | | |
| | 0 | 648 | | matchedRow.File2Data.Add(rowFile2); |
| | 0 | 649 | | rowsToRemove.Add(rowFile2); |
| | | 650 | | } |
| | | 651 | | } |
| | | 652 | | |
| | 0 | 653 | | matchedRows.Add(matchedRow); |
| | | 654 | | |
| | 0 | 655 | | foreach (var row in rowsToRemove) |
| | | 656 | | { |
| | 0 | 657 | | dataFile2.Remove(row); |
| | | 658 | | } |
| | | 659 | | } |
| | | 660 | | |
| | 0 | 661 | | foreach (var rowFile2 in dataFile2) |
| | | 662 | | { |
| | 0 | 663 | | unmatchedRowsFromFile2.Add(rowFile2); |
| | | 664 | | } |
| | | 665 | | |
| | 0 | 666 | | foreach (var unmatchedRow in unmatchedRowsFromFile2) |
| | | 667 | | { |
| | 0 | 668 | | matchedRows.Add(new MatchedRowModel |
| | 0 | 669 | | { |
| | 0 | 670 | | File1Data = null, |
| | 0 | 671 | | File2Data = new List<Dictionary<string, string>> { unmatchedRow } |
| | 0 | 672 | | }); |
| | | 673 | | } |
| | | 674 | | |
| | 0 | 675 | | return matchedRows; |
| | 0 | 676 | | } |
| | | 677 | | |
| | | 678 | | public async Task<List<MatchedRowModel>> MatchExcelDataAsync( |
| | | 679 | | List<MatchedRowModel> matchedRows, |
| | | 680 | | Stream file1Stream, |
| | | 681 | | Stream file2Stream, |
| | | 682 | | List<MatchingColumn> matchingColumns, |
| | | 683 | | int startRow1, |
| | | 684 | | int startColumn1, |
| | | 685 | | int startRow2, |
| | | 686 | | int startColumn2) |
| | | 687 | | { |
| | 0 | 688 | | if (file1Stream == null || file2Stream == null || matchingColumns == null || matchedRows == null) |
| | | 689 | | { |
| | 0 | 690 | | return matchedRows ?? new List<MatchedRowModel>(); |
| | | 691 | | } |
| | | 692 | | |
| | 0 | 693 | | var headersFile1 = await GetTableHeadersAsync(file1Stream, startRow1, startColumn1); |
| | 0 | 694 | | file1Stream.Position = 0; |
| | 0 | 695 | | var dataFile1 = await GetTableDataAsync(file1Stream, startRow1, startColumn1); |
| | | 696 | | |
| | 0 | 697 | | var headersFile2 = await GetTableHeadersAsync(file2Stream, startRow2, startColumn2); |
| | 0 | 698 | | file2Stream.Position = 0; |
| | 0 | 699 | | var dataFile2 = await GetTableDataAsync(file2Stream, startRow2, startColumn2); |
| | | 700 | | |
| | 0 | 701 | | if (headersFile1 == null || headersFile2 == null || dataFile1 == null || dataFile2 == null) |
| | | 702 | | { |
| | 0 | 703 | | return matchedRows; |
| | | 704 | | } |
| | | 705 | | |
| | 0 | 706 | | headersFile1 = headersFile1.Distinct().ToList(); |
| | 0 | 707 | | headersFile2 = headersFile2.Distinct().ToList(); |
| | | 708 | | |
| | 0 | 709 | | var existingRows = new HashSet<string>( |
| | 0 | 710 | | matchedRows.SelectMany(m => m.File2Data ?? new List<Dictionary<string, string>>()) |
| | 0 | 711 | | .Select(row => string.Join("|", row?.Values?.ToList() ?? new List<string>()))); |
| | | 712 | | |
| | | 713 | | |
| | 0 | 714 | | foreach (var rowFile1 in dataFile1) |
| | | 715 | | { |
| | 0 | 716 | | if (rowFile1 == null) continue; |
| | | 717 | | |
| | 0 | 718 | | var matchedRow = new MatchedRowModel |
| | 0 | 719 | | { |
| | 0 | 720 | | File1Data = rowFile1, |
| | 0 | 721 | | File2Data = new List<Dictionary<string, string>>() |
| | 0 | 722 | | }; |
| | | 723 | | |
| | 0 | 724 | | foreach (var rowFile2 in dataFile2) |
| | | 725 | | { |
| | 0 | 726 | | if (rowFile2 == null) continue; |
| | | 727 | | |
| | 0 | 728 | | bool isMatch = matchingColumns.All(match => |
| | 0 | 729 | | { |
| | 0 | 730 | | if (string.IsNullOrEmpty(match.Item1) || string.IsNullOrEmpty(match.Item2) || |
| | 0 | 731 | | !rowFile1.ContainsKey(match.Item1) || !rowFile2.ContainsKey(match.Item2)) |
| | 0 | 732 | | { |
| | 0 | 733 | | return false; |
| | 0 | 734 | | } |
| | 0 | 735 | | |
| | 0 | 736 | | var value1 = rowFile1[match.Item1]; |
| | 0 | 737 | | var value2 = rowFile2[match.Item2]; |
| | 0 | 738 | | |
| | 0 | 739 | | return CompareValues(value1, value2); |
| | 0 | 740 | | }); |
| | | 741 | | |
| | 0 | 742 | | if (isMatch) |
| | | 743 | | { |
| | 0 | 744 | | var rowKey = string.Join("|", rowFile2.Values); |
| | 0 | 745 | | if (!existingRows.Contains(rowKey)) |
| | | 746 | | { |
| | 0 | 747 | | matchedRow.File2Data.Add(rowFile2); |
| | 0 | 748 | | existingRows.Add(rowKey); |
| | | 749 | | } |
| | | 750 | | } |
| | | 751 | | } |
| | | 752 | | |
| | 0 | 753 | | if (matchedRow.File2Data.Any()) |
| | | 754 | | { |
| | 0 | 755 | | matchedRows.Add(matchedRow); |
| | | 756 | | } |
| | | 757 | | } |
| | | 758 | | |
| | 0 | 759 | | return matchedRows; |
| | 0 | 760 | | } |
| | | 761 | | |
| | | 762 | | |
| | | 763 | | private bool CompareValues(object value1, object value2) |
| | | 764 | | { |
| | 0 | 765 | | var culture = _culture; |
| | | 766 | | |
| | 0 | 767 | | var formats = new[] { "d.M.yyyy", "yyyy-MM-dd HH:mm:ss" }; |
| | | 768 | | |
| | 0 | 769 | | if (DateTime.TryParseExact(value1?.ToString(), formats, culture, DateTimeStyles.None, out DateTime date1) && |
| | 0 | 770 | | DateTime.TryParseExact(value2?.ToString(), formats, culture, DateTimeStyles.None, out DateTime date2)) |
| | | 771 | | { |
| | 0 | 772 | | return date1.Date == date2.Date; |
| | | 773 | | } |
| | | 774 | | |
| | 0 | 775 | | if (decimal.TryParse(value1?.ToString(), NumberStyles.Any, culture, out decimal decimal1) && |
| | 0 | 776 | | decimal.TryParse(value2?.ToString(), NumberStyles.Any, culture, out decimal decimal2)) |
| | | 777 | | { |
| | 0 | 778 | | return Math.Floor(decimal1) == Math.Floor(decimal2); |
| | | 779 | | } |
| | | 780 | | |
| | 0 | 781 | | if (int.TryParse(value1?.ToString(), NumberStyles.Any, culture, out int int1) && |
| | 0 | 782 | | int.TryParse(value2?.ToString(), NumberStyles.Any, culture, out int int2)) |
| | | 783 | | { |
| | 0 | 784 | | return int1 == int2; |
| | | 785 | | } |
| | | 786 | | |
| | 0 | 787 | | return string.Equals(value1?.ToString(), value2?.ToString(), StringComparison.OrdinalIgnoreCase); |
| | | 788 | | } |
| | | 789 | | |
| | | 790 | | public async Task<(List<Dictionary<string, string>> TableData, DateTime? DocumentDate)> |
| | | 791 | | GetTableDataFromXlsAsync( |
| | | 792 | | Stream excelStream, int startRow = 1, int startColumn = 1, int dateRow = 5, int dateColumn = 7) |
| | | 793 | | { |
| | 0 | 794 | | return await Task.Run(() => |
| | 0 | 795 | | { |
| | 0 | 796 | | var tableData = new List<Dictionary<string, string>>(); |
| | 0 | 797 | | DateTime? documentDate = null; |
| | 0 | 798 | | |
| | 0 | 799 | | // Сбрасываем позицию потока |
| | 0 | 800 | | if (excelStream.CanSeek) |
| | 0 | 801 | | { |
| | 0 | 802 | | excelStream.Seek(0, SeekOrigin.Begin); |
| | 0 | 803 | | } |
| | 0 | 804 | | |
| | 0 | 805 | | using (var workbook = new HSSFWorkbook(excelStream, true)) // true = leaveOpen |
| | 0 | 806 | | { |
| | 0 | 807 | | var worksheet = workbook.GetSheetAt(0); // Первый лист |
| | 0 | 808 | | |
| | 0 | 809 | | // Сначала получаем дату документа |
| | 0 | 810 | | documentDate = GetDateFromWorksheet(worksheet, dateRow, dateColumn); |
| | 0 | 811 | | |
| | 0 | 812 | | // Затем обрабатываем строки с данными |
| | 0 | 813 | | for (int rowIndex = startRow - 1; rowIndex <= worksheet.LastRowNum; rowIndex++) |
| | 0 | 814 | | { |
| | 0 | 815 | | var row = worksheet.GetRow(rowIndex); |
| | 0 | 816 | | if (row == null) continue; |
| | 0 | 817 | | |
| | 0 | 818 | | var rowData = new Dictionary<string, string>(); |
| | 0 | 819 | | bool rowIsEmpty = true; |
| | 0 | 820 | | |
| | 0 | 821 | | // Обрабатываем ячейки в строке |
| | 0 | 822 | | for (int col = startColumn - 1; col < row.LastCellNum; col++) |
| | 0 | 823 | | { |
| | 0 | 824 | | var cell = row.GetCell(col); |
| | 0 | 825 | | string cellText = GetCellValue(cell); |
| | 0 | 826 | | |
| | 0 | 827 | | // Используем числовой индекс как ключ (начинаем с 1 для удобства) |
| | 0 | 828 | | string columnKey = (col - (startColumn - 1) + 1).ToString(); |
| | 0 | 829 | | |
| | 0 | 830 | | // Обработка цен (предполагаем, что цена в столбце с индексом 7, считая с 1) |
| | 0 | 831 | | if (columnKey == "7") // price(RUR) столбец |
| | 0 | 832 | | { |
| | 0 | 833 | | ProcessPriceCell(cellText, rowData); |
| | 0 | 834 | | } |
| | 0 | 835 | | |
| | 0 | 836 | | if (!string.IsNullOrWhiteSpace(cellText)) |
| | 0 | 837 | | { |
| | 0 | 838 | | rowIsEmpty = false; |
| | 0 | 839 | | } |
| | 0 | 840 | | |
| | 0 | 841 | | // Всегда добавляем данные, даже если пустые |
| | 0 | 842 | | rowData[columnKey] = cellText; |
| | 0 | 843 | | } |
| | 0 | 844 | | |
| | 0 | 845 | | // Добавляем дополнительные поля для частей цены |
| | 0 | 846 | | if (!rowData.ContainsKey("Целая часть")) |
| | 0 | 847 | | rowData["Целая часть"] = string.Empty; |
| | 0 | 848 | | if (!rowData.ContainsKey("Дробная часть")) |
| | 0 | 849 | | rowData["Дробная часть"] = string.Empty; |
| | 0 | 850 | | |
| | 0 | 851 | | if (!rowIsEmpty) |
| | 0 | 852 | | { |
| | 0 | 853 | | tableData.Add(rowData); |
| | 0 | 854 | | } |
| | 0 | 855 | | } |
| | 0 | 856 | | } |
| | 0 | 857 | | |
| | 0 | 858 | | return (tableData, documentDate); |
| | 0 | 859 | | }); |
| | 0 | 860 | | } |
| | | 861 | | |
| | | 862 | | // Вспомогательный метод для получения даты из worksheet |
| | | 863 | | private DateTime? GetDateFromWorksheet(ISheet worksheet, int rowNumber, int columnNumber) |
| | | 864 | | { |
| | | 865 | | try |
| | | 866 | | { |
| | 0 | 867 | | var row = worksheet.GetRow(rowNumber - 1); // -1 потому что 0-based |
| | 0 | 868 | | if (row == null) return null; |
| | | 869 | | |
| | 0 | 870 | | var cell = row.GetCell(columnNumber - 1); // -1 потому что 0-based |
| | 0 | 871 | | if (cell == null) return null; |
| | | 872 | | |
| | | 873 | | // Обрабатываем разные типы ячеек |
| | 0 | 874 | | switch (cell.CellType) |
| | | 875 | | { |
| | | 876 | | case CellType.Numeric: |
| | 0 | 877 | | if (DateUtil.IsCellDateFormatted(cell)) |
| | | 878 | | { |
| | 0 | 879 | | return cell.DateCellValue; |
| | | 880 | | } |
| | | 881 | | else |
| | | 882 | | { |
| | 0 | 883 | | string stringValue = cell.NumericCellValue.ToString(CultureInfo.InvariantCulture); |
| | 0 | 884 | | return ParseDateString(stringValue); |
| | | 885 | | } |
| | | 886 | | |
| | | 887 | | case CellType.String: |
| | 0 | 888 | | return ParseDateString(cell.StringCellValue); |
| | | 889 | | |
| | | 890 | | case CellType.Formula: |
| | | 891 | | try |
| | | 892 | | { |
| | 0 | 893 | | if (cell.CachedFormulaResultType == CellType.Numeric && |
| | 0 | 894 | | DateUtil.IsCellDateFormatted(cell)) |
| | | 895 | | { |
| | 0 | 896 | | return cell.DateCellValue; |
| | | 897 | | } |
| | | 898 | | else |
| | | 899 | | { |
| | 0 | 900 | | return ParseDateString(cell.ToString()); |
| | | 901 | | } |
| | | 902 | | } |
| | 0 | 903 | | catch |
| | | 904 | | { |
| | 0 | 905 | | return ParseDateString(cell.ToString()); |
| | | 906 | | } |
| | | 907 | | |
| | | 908 | | default: |
| | 0 | 909 | | return ParseDateString(cell.ToString()); |
| | | 910 | | } |
| | | 911 | | } |
| | 0 | 912 | | catch (Exception ex) |
| | | 913 | | { |
| | 0 | 914 | | Console.WriteLine($"Ошибка при чтении даты: {ex.Message}"); |
| | 0 | 915 | | return null; |
| | | 916 | | } |
| | 0 | 917 | | } |
| | | 918 | | |
| | | 919 | | // Вспомогательный метод для парсинга даты из строки |
| | | 920 | | private DateTime? ParseDateString(string? dateString) |
| | | 921 | | { |
| | 0 | 922 | | if (string.IsNullOrWhiteSpace(dateString)) |
| | 0 | 923 | | return null; |
| | | 924 | | |
| | 0 | 925 | | dateString = dateString.Trim().Replace("\"", ""); |
| | | 926 | | |
| | 0 | 927 | | string[] formats = |
| | 0 | 928 | | { |
| | 0 | 929 | | "dd.MM.yyyy", "d.M.yyyy", "dd/MM/yyyy", "d/M/yyyy", |
| | 0 | 930 | | "MM/dd/yyyy", "M/d/yyyy", "yyyy-MM-dd", "yyyy-M-d", |
| | 0 | 931 | | "dd.MM.yy", "d.M.yy", "dd/MM/yy", "d/M/yy" |
| | 0 | 932 | | }; |
| | | 933 | | |
| | 0 | 934 | | if (DateTime.TryParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, |
| | 0 | 935 | | out DateTime result)) |
| | | 936 | | { |
| | 0 | 937 | | return result; |
| | | 938 | | } |
| | | 939 | | |
| | 0 | 940 | | if (DateTime.TryParse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.None, out result)) |
| | | 941 | | { |
| | 0 | 942 | | return result; |
| | | 943 | | } |
| | | 944 | | |
| | 0 | 945 | | Console.WriteLine($"Не удалось распарсить дату: '{dateString}'"); |
| | 0 | 946 | | return null; |
| | | 947 | | } |
| | | 948 | | |
| | | 949 | | // Вспомогательный метод для обработки цены |
| | | 950 | | private void ProcessPriceCell(string cellText, Dictionary<string, string> rowData) |
| | | 951 | | { |
| | 0 | 952 | | string normalizedText = cellText.Replace(" ", "").Replace("'", ""); |
| | | 953 | | string[] parts; |
| | | 954 | | |
| | 0 | 955 | | if (normalizedText.Contains(',')) |
| | | 956 | | { |
| | 0 | 957 | | parts = normalizedText.Split(','); |
| | | 958 | | } |
| | 0 | 959 | | else if (normalizedText.Contains('.')) |
| | | 960 | | { |
| | 0 | 961 | | parts = normalizedText.Split('.'); |
| | | 962 | | } |
| | | 963 | | else |
| | | 964 | | { |
| | 0 | 965 | | parts = new string[] { normalizedText }; |
| | | 966 | | } |
| | | 967 | | |
| | 0 | 968 | | if (parts.Length == 2) |
| | | 969 | | { |
| | 0 | 970 | | rowData["Целая часть"] = parts[0]; |
| | 0 | 971 | | rowData["Дробная часть"] = parts[1]; |
| | 0 | 972 | | Console.WriteLine($"Разделено: целая='{parts[0]}', дробная='{parts[1]}'"); |
| | | 973 | | } |
| | 0 | 974 | | else if (parts.Length == 1) |
| | | 975 | | { |
| | 0 | 976 | | rowData["Целая часть"] = parts[0]; |
| | 0 | 977 | | rowData["Дробная часть"] = "0"; |
| | 0 | 978 | | Console.WriteLine($"Только целая часть: '{parts[0]}'"); |
| | | 979 | | } |
| | | 980 | | else |
| | | 981 | | { |
| | 0 | 982 | | rowData["Целая часть"] = string.Empty; |
| | 0 | 983 | | rowData["Дробная часть"] = string.Empty; |
| | 0 | 984 | | Console.WriteLine($"Некорректный формат цены: '{cellText}'"); |
| | | 985 | | } |
| | 0 | 986 | | } |
| | | 987 | | |
| | | 988 | | // Вспомогательный метод для получения значения ячейки |
| | | 989 | | private string GetCellValue(ICell cell) |
| | | 990 | | { |
| | 0 | 991 | | if (cell == null) return string.Empty; |
| | | 992 | | |
| | 0 | 993 | | switch (cell.CellType) |
| | | 994 | | { |
| | | 995 | | case CellType.String: |
| | 0 | 996 | | return cell.StringCellValue?.Trim() ?? string.Empty; |
| | | 997 | | case CellType.Numeric: |
| | 0 | 998 | | if (DateUtil.IsCellDateFormatted(cell)) |
| | | 999 | | { |
| | 0 | 1000 | | return cell.DateCellValue?.ToString() ?? string.Empty; |
| | | 1001 | | } |
| | | 1002 | | |
| | 0 | 1003 | | return cell.NumericCellValue.ToString(CultureInfo.InvariantCulture); |
| | | 1004 | | case CellType.Boolean: |
| | 0 | 1005 | | return cell.BooleanCellValue.ToString(); |
| | | 1006 | | case CellType.Formula: |
| | | 1007 | | try |
| | | 1008 | | { |
| | 0 | 1009 | | if (cell.CachedFormulaResultType == CellType.String) |
| | 0 | 1010 | | return cell.StringCellValue?.Trim() ?? string.Empty; |
| | 0 | 1011 | | else if (cell.CachedFormulaResultType == CellType.Numeric) |
| | 0 | 1012 | | return cell.NumericCellValue.ToString(CultureInfo.InvariantCulture); |
| | 0 | 1013 | | else if (cell.CachedFormulaResultType == CellType.Boolean) |
| | 0 | 1014 | | return cell.BooleanCellValue.ToString(); |
| | | 1015 | | else |
| | 0 | 1016 | | return cell.ToString()?.Trim() ?? string.Empty; |
| | | 1017 | | } |
| | 0 | 1018 | | catch |
| | | 1019 | | { |
| | 0 | 1020 | | return cell.ToString()?.Trim() ?? string.Empty; |
| | | 1021 | | } |
| | | 1022 | | default: |
| | 0 | 1023 | | return cell.ToString()?.Trim() ?? string.Empty; |
| | | 1024 | | } |
| | 0 | 1025 | | } |
| | | 1026 | | } |
| | | 1027 | | } |