18using DocumentFormat.OpenXml.Spreadsheet;
20using System.Collections.Generic;
48 private List<string> _filePaths;
49 private Dictionary<string, XLWorkbook> _workbooks;
50 private string _currentSheetName;
51 private int _currentSheetIndex {
get;
set; }
52 List<ExcelHelper.CellDifference> _differences;
53 private int? _insertPosition;
54 private string _insertSeparator;
55 private string _replaceValue;
56 private string _currentCell;
57 private bool _operationPerformed;
58 private bool _isClosed;
59 private List<(
string Sheet,
string Range, IGPALGrid<string> Data)> _rangesData;
67 _filePaths =
new List<string>();
68 _workbooks =
new Dictionary<string, XLWorkbook>();
69 _rangesData =
new List<(
string Sheet,
string Range, IGPALGrid<string> Data)>();
70 _differences =
new List<ExcelHelper.CellDifference>();
72 _insertSeparator =
" ";
73 _operationPerformed =
false;
83 private void ReopenIfClosed()
91 _currentSheetName =
null;
92 _currentSheetIndex = -1;
94 _insertSeparator =
" ";
102 $
"Reopening already closed file [{_gpalFile?.Filenames?.FirstOrDefault() ?? "unknown
"}]",
104 GPALObjectType.Other);
114 private void LoadFile(
string path)
116 if (!_workbooks.ContainsKey(path))
120 _workbooks[path] =
new XLWorkbook(path);
123 $
"Loaded workbook [{path}]",
125 GPALObjectType.GPALExcel);
131 $
"Failed to load workbook [{path}]",
133 GPALObjectType.GPALExcel, ex);
152 if (gpalFile ==
null)
156 "GPALFile cannot be null",
158 GPALObjectType.GPALExcel);
162 _gpalFile = gpalFile;
166 _differences.Clear();
167 _currentSheetName =
null;
168 _currentSheetIndex = -1;
170 _insertSeparator =
" ";
173 _operationPerformed =
false;
175 foreach (var pattern
in gpalFile.
Filenames)
179 string directory = Path.GetDirectoryName(pattern) ?? Directory.GetCurrentDirectory();
180 string fileName = Path.GetFileName(pattern);
181 var matchingFiles = Directory.GetFiles(directory, fileName, SearchOption.TopDirectoryOnly);
182 _filePaths.AddRange(matchingFiles);
188 $
"Failed to resolve wildcard pattern [{pattern}]",
190 GPALObjectType.GPALExcel, ex);
194 _filePaths = _filePaths.Distinct().ToList();
195 foreach (var path
in _filePaths)
213 if (!_workbooks.Any())
217 "No workbooks loaded",
219 GPALObjectType.GPALExcel);
226 foreach (var kvp
in _workbooks)
227 if (1 > sheetIndex || sheetIndex > kvp.Value.Worksheets.Count)
230 if (indexErrors == _workbooks.Count)
233 $
"Invalid sheet index. No workbook contains sheet [{sheetIndex}]",
235 GPALObjectType.GPALExcel);
238 _currentSheetName =
null;
239 _currentSheetIndex = sheetIndex;
255 if (
string.IsNullOrEmpty(sheetName))
259 "Sheet name cannot be empty",
261 GPALObjectType.GPALExcel);
267 foreach (var kvp
in _workbooks)
269 if (!kvp.Value.Worksheets.Any(ws => ws.Name.Equals(sheetName, StringComparison.OrdinalIgnoreCase)))
273 if (nameErrors == _workbooks.Count)
276 $
"Sheet [{sheetName}] not found in any workbooks",
278 GPALObjectType.GPALExcel);
281 _currentSheetName = sheetName;
282 _currentSheetIndex = -1;
300 if (
string.IsNullOrEmpty(range))
304 "Range cannot be empty",
306 GPALObjectType.Other);
310 if (
true == _operationPerformed)
313 _operationPerformed =
false;
314 _differences.Clear();
317 foreach (var kvp
in _workbooks)
319 var worksheet = GetWorksheet(kvp.Value);
322 if (worksheet !=
null)
324 var rangeData = ExcelHelper.ReadRange(worksheet, range);
325 _rangesData.Add((_currentSheetName ?? _currentSheetIndex.ToString() ??
"Sheet1", range, rangeData));
331 $
"Cannot read range [{range}] from [{worksheet?.Name ?? "unknown
"}]: Invalid sheet",
333 GPALObjectType.Other);
340 $
"Failed to read range [{range}] from [{worksheet?.Name ?? "unknown
"}]",
342 GPALObjectType.Other, ex);
360 _operationPerformed =
true;
362 if (!_rangesData.Any())
366 $
"No data to write for range [{range}]",
368 GPALObjectType.Other);
370 else if (
string.IsNullOrEmpty(range))
374 "Range cannot be empty",
376 GPALObjectType.Other);
380 foreach (var kvp
in _workbooks)
384 var worksheet = GetWorksheet(kvp.Value);
385 if (worksheet !=
null)
387 foreach (var rangeData
in _rangesData)
389 ExcelHelper.WriteRange(worksheet, range, rangeData.Data);
396 $
"Cannot write range [{range}] to [{kvp.Key}]: Invalid sheet",
398 GPALObjectType.Other);
405 $
"Failed to write range [{range}] to [{kvp.Key}]",
407 GPALObjectType.Other, ex);
424 _differences.Clear();
427 "Cleared range data and comparison differences",
429 GPALObjectType.GPALExcel);
444 if (
string.IsNullOrEmpty(cell))
448 "Cell address cannot be empty",
450 GPALObjectType.GPALExcel);
470 if (
string.IsNullOrEmpty(value))
474 "Search value cannot be empty",
476 GPALObjectType.GPALExcel);
479 _replaceValue = value;
496 if (
true == _operationPerformed)
499 _operationPerformed =
false;
500 _differences.Clear();
503 if (
string.IsNullOrEmpty(column))
507 "Column cannot be empty",
509 GPALObjectType.GPALExcel);
513 foreach (var kvp
in _workbooks)
517 var worksheet = GetWorksheet(kvp.Value);
518 if (worksheet !=
null)
520 var values = ExcelHelper.GetColumnValues(worksheet, column);
521 var grid =
GPAL.GridForType<
string>();
522 foreach (var value
in values)
523 grid.AddRow(
new List<string> { value });
524 _rangesData.Add((_currentSheetName ?? _currentSheetIndex.ToString() ??
"Sheet1", column, grid));
529 $
"Cannot read column [{column}] from [{kvp.Key}]: Invalid sheet",
531 GPALObjectType.GPALExcel);
537 $
"Failed to read column [{column}] from [{kvp.Key}]",
539 GPALObjectType.GPALExcel, ex);
558 if (
true == _operationPerformed)
561 _operationPerformed =
false;
562 _differences.Clear();
569 $
"Invalid row number [{rowNumber}]",
571 GPALObjectType.GPALExcel);
575 foreach (var kvp
in _workbooks)
579 var worksheet = GetWorksheet(kvp.Value);
580 if (worksheet !=
null)
582 var values = ExcelHelper.GetRowValues(worksheet, rowNumber);
583 var grid =
GPAL.GridForType<
string>();
584 grid.AddRow(values.ToList());
585 _rangesData.Add((_currentSheetName ?? _currentSheetIndex.ToString() ??
"Sheet1", $
"Row{rowNumber}", grid));
592 $
"Cannot read row [{rowNumber}] from [{kvp.Key}]: Invalid sheet",
594 GPALObjectType.GPALExcel);
601 $
"Failed to read row [{rowNumber}] from [{kvp.Key}]",
603 GPALObjectType.GPALExcel, ex);
620 _operationPerformed =
true;
622 if (!_rangesData.Any())
628 GPALObjectType.GPALExcel);
634 var sum = _rangesData
635 .SelectMany(rd => rd.Data.SelectMany(row => row))
636 .Where(v =>
double.TryParse(v, out _))
637 .Sum(v =>
double.Parse(v));
638 result = sum.ToString();
644 $
"Failed to calculate sum",
646 GPALObjectType.GPALExcel, ex);
662 _operationPerformed =
true;
664 if (!_rangesData.Any())
670 GPALObjectType.GPALExcel);
676 var count = _rangesData
677 .SelectMany(rd => rd.Data.SelectMany(row => row))
678 .Count(v => !
string.IsNullOrEmpty(v));
679 result = count.ToString();
685 $
"Failed to calculate count",
687 GPALObjectType.GPALExcel, ex);
702 _operationPerformed =
true;
704 if (!_rangesData.Any())
708 "No range defined for comparison",
710 GPALObjectType.GPALExcel);
714 foreach (var kvp
in _workbooks)
719 foreach (var rangeData
in _rangesData)
723 var ws1 = GetWorksheet(kvp.Value, rangeData.Sheet);
728 $
"Invalid sheet for comparison in [{kvp.Key}]: [{rangeData.Sheet}]",
730 GPALObjectType.GPALExcel);
733 var data1 = ExcelHelper.ReadRange(ws1, rangeData.Range);
734 var differences = ExcelHelper.CompareRanges(data1, data2);
735 foreach (var diff
in differences)
737 _differences.Add(
new ExcelHelper.CellDifference
739 CellAddress = diff.CellAddress,
740 OldValue = diff.OldValue,
741 NewValue = diff.NewValue,
742 SourceRange = rangeData.Range,
751 $
"Failed to compare range [{rangeData.Range}] in [{kvp.Key}]",
753 GPALObjectType.GPALExcel, ex);
761 $
"Failed to compare with grid in [{kvp.Key}]",
763 GPALObjectType.GPALExcel, ex);
780 _operationPerformed =
true;
782 if (gpalFile ==
null)
786 "Comparison file cannot be null",
788 GPALObjectType.GPALExcel);
790 else if (!_rangesData.Any())
794 "No range defined for comparison",
796 GPALObjectType.GPALExcel);
802 var comparePaths =
new List<string>();
803 foreach (var pattern
in gpalFile.
Filenames)
807 string directory = Path.GetDirectoryName(pattern) ?? Directory.GetCurrentDirectory();
808 string fileName = Path.GetFileName(pattern);
809 var matchingFiles = Directory.GetFiles(directory, fileName, SearchOption.TopDirectoryOnly);
810 comparePaths.AddRange(matchingFiles);
816 $
"Failed to resolve wildcard pattern [{pattern}]",
818 GPALObjectType.GPALExcel, ex);
821 comparePaths = comparePaths.Distinct().ToList();
823 foreach (var kvp
in _workbooks)
825 var worksheet = GetWorksheet(kvp.Value);
826 if (worksheet ==
null)
830 $
"Invalid sheet in [{kvp.Key}]",
832 GPALObjectType.GPALExcel);
835 foreach (var comparePath
in comparePaths)
839 using var compareWorkbook =
new XLWorkbook(comparePath);
840 var compareWorksheet = GetWorksheet(compareWorkbook, _currentSheetName) ?? GetWorksheet(compareWorkbook, _currentSheetIndex);
841 if (compareWorksheet ==
null)
845 $
"Sheet [{_currentSheetName ?? _currentSheetIndex.ToString()}] not found in [{comparePath}]",
847 GPALObjectType.GPALExcel);
850 foreach (var rangeData
in _rangesData)
854 var data1 = ExcelHelper.ReadRange(worksheet, rangeData.Range);
855 var data2 = ExcelHelper.ReadRange(compareWorksheet, rangeData.Range);
856 var differences = ExcelHelper.CompareRanges(data1, data2);
857 foreach (var diff
in differences)
859 _differences.Add(
new ExcelHelper.CellDifference
861 CellAddress = diff.CellAddress,
862 OldValue = diff.OldValue,
863 NewValue = diff.NewValue,
864 SourceRange = rangeData.Range,
865 TargetRange = $
"{comparePath}:{rangeData.Range}"
873 $
"Failed to compare range [{rangeData.Range}] in [{kvp.Key}] with [{comparePath}]",
875 GPALObjectType.GPALExcel, ex);
883 $
"Failed to compare [{kvp.Key}] with [{comparePath}]",
885 GPALObjectType.GPALExcel, ex);
893 GPALEventType.EXCEPTION,
894 $
"Failed to compare with files [{string.Join(",
", gpalFile.Filenames)}]",
896 GPALObjectType.GPALExcel, ex);
911 _operationPerformed =
true;
913 if (!_rangesData.Any())
917 "No initial range defined for comparison",
919 GPALObjectType.GPALExcel);
921 else if (
string.IsNullOrEmpty(range))
925 "Comparison range cannot be empty",
927 GPALObjectType.GPALExcel);
931 foreach (var kvp
in _workbooks)
935 var ws2 = GetWorksheet(kvp.Value);
940 $
"Invalid sheet for comparison in [{kvp.Key}]",
942 GPALObjectType.GPALExcel);
945 var data2 = ExcelHelper.ReadRange(ws2, range);
946 foreach (var rangeData
in _rangesData)
950 var ws1 = GetWorksheet(kvp.Value, rangeData.Sheet);
955 $
"Invalid sheet for comparison in [{kvp.Key}]: [{rangeData.Sheet}]",
957 GPALObjectType.GPALExcel);
960 var data1 = ExcelHelper.ReadRange(ws1, rangeData.Range);
961 var differences = ExcelHelper.CompareRanges(data1, data2);
962 foreach (var diff
in differences)
964 _differences.Add(
new ExcelHelper.CellDifference
966 CellAddress = diff.CellAddress,
967 OldValue = diff.OldValue,
968 NewValue = diff.NewValue,
969 SourceRange = rangeData.Range,
978 $
"Failed to compare range [{rangeData.Range}] in [{kvp.Key}]",
980 GPALObjectType.GPALExcel, ex);
988 $
"Failed to compare ranges in [{kvp.Key}]",
990 GPALObjectType.GPALExcel, ex);
1008 results =
GPAL.GridForType<
string>();
1009 results.AddRow(
new List<string> {
"File",
"Sheet",
"Cell",
"SourceRange",
"TargetRange",
"OldValue",
"NewValue" });
1013 if (_differences.Any())
1015 foreach (var diff
in _differences)
1017 results.AddRow(
new List<string>
1019 _filePaths.FirstOrDefault() ??
"unknown",
1020 _currentSheetName ?? _currentSheetIndex.ToString() ??
"unknown",
1030 catch (Exception ex)
1033 GPALEventType.ERROR,
1034 $
"Failed to get results",
1036 GPALObjectType.GPALExcel, ex);
1054 GPALEventType.ERROR,
1055 $
"Invalid insert position [{position}]",
1057 GPALObjectType.GPALExcel);
1060 _insertPosition = position;
1075 if (
string.IsNullOrEmpty(separator))
1078 GPALEventType.ERROR,
1079 "Insert separator cannot be empty",
1081 GPALObjectType.GPALExcel);
1084 _insertSeparator = separator;
1102 _operationPerformed =
true;
1104 if (_insertPosition ==
null || _insertSeparator ==
null ||
string.IsNullOrEmpty(_currentCell))
1107 GPALEventType.ERROR,
1108 $
"Missing insert position, separator, or cell for value [{value}]",
1110 GPALObjectType.GPALExcel);
1115 foreach (var kvp
in _workbooks)
1119 var worksheet = GetWorksheet(kvp.Value);
1120 if (worksheet !=
null)
1122 var cell = worksheet.Cell(_currentCell);
1123 var currentValue = cell.GetString();
1124 var newValue = _insertPosition == 0 ? $
"{value}{_insertSeparator}{currentValue}" : $
"{currentValue}{_insertSeparator}{value}";
1125 cell.SetValue(newValue);
1130 GPALEventType.ERROR,
1131 $
"Cannot insert value [{value}] in [{kvp.Key}]: Invalid sheet",
1133 GPALObjectType.GPALExcel);
1136 catch (Exception ex)
1139 GPALEventType.ERROR,
1140 $
"Failed to insert value [{value}] at cell [{_currentCell}] in [{kvp.Key}]",
1142 GPALObjectType.GPALExcel, ex);
1160 _operationPerformed =
true;
1162 if (
string.IsNullOrEmpty(_currentCell))
1165 GPALEventType.ERROR,
1166 $
"No cell specified for setting value [{value}]",
1168 GPALObjectType.GPALExcel);
1172 foreach (var kvp
in _workbooks)
1176 var worksheet = GetWorksheet(kvp.Value);
1177 if (worksheet !=
null)
1179 worksheet.Cell(_currentCell).SetValue(value);
1184 GPALEventType.ERROR,
1185 $
"Cannot set value [{value}] in [{kvp.Key}]: Invalid sheet",
1187 GPALObjectType.GPALExcel);
1190 catch (Exception ex)
1193 GPALEventType.ERROR,
1194 $
"Failed to set value [{value}] at cell [{_currentCell}] in [{kvp.Key}]",
1196 GPALObjectType.GPALExcel, ex);
1214 _operationPerformed =
true;
1216 if (
string.IsNullOrEmpty(_currentCell))
1219 GPALEventType.ERROR,
1220 $
"No cell specified for appending value [{value}]",
1222 GPALObjectType.GPALExcel);
1226 foreach (var kvp
in _workbooks)
1230 var worksheet = GetWorksheet(kvp.Value);
1231 if (worksheet !=
null)
1233 var cell = worksheet.Cell(_currentCell);
1234 var currentValue = cell.GetString();
1235 cell.SetValue(currentValue + value);
1240 GPALEventType.ERROR,
1241 $
"Cannot append value [{value}] in [{kvp.Key}]: Invalid sheet",
1243 GPALObjectType.GPALExcel);
1246 catch (Exception ex)
1249 GPALEventType.ERROR,
1250 $
"Failed to append value [{value}] at cell [{_currentCell}] in [{kvp.Key}]",
1252 GPALObjectType.GPALExcel, ex);
1270 _operationPerformed =
true;
1272 if (
string.IsNullOrEmpty(_currentCell))
1275 GPALEventType.ERROR,
1276 $
"No cell specified for prepending value [{value}]",
1278 GPALObjectType.GPALExcel);
1282 foreach (var kvp
in _workbooks)
1286 var worksheet = GetWorksheet(kvp.Value);
1287 if (worksheet !=
null)
1289 var cell = worksheet.Cell(_currentCell);
1290 var currentValue = cell.GetString();
1291 cell.SetValue(value + currentValue);
1296 GPALEventType.ERROR,
1297 $
"Cannot prepend value [{value}] in [{kvp.Key}]: Invalid sheet",
1299 GPALObjectType.GPALExcel);
1302 catch (Exception ex)
1305 GPALEventType.ERROR,
1306 $
"Failed to prepend value [{value}] at cell [{_currentCell}] in [{kvp.Key}]",
1308 GPALObjectType.GPALExcel, ex);
1325 _operationPerformed =
true;
1327 if (
string.IsNullOrEmpty(_replaceValue))
1330 GPALEventType.ERROR,
1331 $
"No search value for replace with [{value}]",
1333 GPALObjectType.GPALExcel);
1335 else if (!_rangesData.Any())
1338 GPALEventType.ERROR,
1339 $
"No range defined for replace with [{value}]",
1341 GPALObjectType.GPALExcel);
1345 foreach (var kvp
in _workbooks)
1349 var worksheet = GetWorksheet(kvp.Value);
1350 if (worksheet ==
null)
1353 GPALEventType.ERROR,
1354 $
"Cannot replace in [{kvp.Key}]: Invalid sheet",
1356 GPALObjectType.GPALExcel);
1360 foreach (var rangeData
in _rangesData)
1362 ExcelHelper.SearchAndReplaceByValue(worksheet, rangeData.Range, _replaceValue, value);
1366 catch (Exception ex)
1369 GPALEventType.ERROR,
1370 $
"Failed to replace [{_replaceValue}] with [{value}] in [{kvp.Key}]",
1372 GPALObjectType.GPALExcel, ex);
1388 _operationPerformed =
true;
1389 gpalFile = gpalFile ?? _gpalFile;
1391 if (gpalFile ==
null)
1393 GPAL.
PublishSimpleEvent(GPALEventType.ERROR,
"No GPALFile specified for save",
this, GPALObjectType.GPALExcel);
1395 else if (!_workbooks.Any())
1397 GPAL.
PublishSimpleEvent(GPALEventType.ERROR,
"No workbooks loaded to save",
this, GPALObjectType.GPALExcel);
1403 var targetPaths =
new List<string>();
1404 foreach (var pattern
in gpalFile.
Filenames)
1408 string directory = Path.GetDirectoryName(pattern) ?? Directory.GetCurrentDirectory();
1409 string fileName = Path.GetFileName(pattern);
1410 var matchingFiles = Directory.GetFiles(directory, fileName, SearchOption.TopDirectoryOnly);
1411 targetPaths.AddRange(matchingFiles);
1413 catch (Exception ex)
1415 GPAL.
PublishSimpleEvent(GPALEventType.ERROR, $
"Failed to resolve save path [{pattern}]",
this, GPALObjectType.GPALExcel, ex);
1418 targetPaths = targetPaths.Distinct().ToList();
1420 if (!targetPaths.Any())
1422 GPAL.
PublishSimpleEvent(GPALEventType.ERROR, $
"No valid target paths resolved from [{string.Join(",
", gpalFile.Filenames)}]",
this, GPALObjectType.GPALExcel);
1426 foreach (var kvp
in _workbooks)
1430 if (targetPaths.Contains(kvp.Key, StringComparer.OrdinalIgnoreCase))
1434 kvp.Value.SaveAs(kvp.Key);
1435 GPAL.
PublishSimpleEvent(GPALEventType.INFO, $
"Saved workbook [{kvp.Key}] to [{kvp.Key}]",
this, GPALObjectType.GPALExcel);
1437 catch (Exception ex)
1439 GPAL.
PublishSimpleEvent(GPALEventType.ERROR, $
"Failed to save workbook [{kvp.Key}] to [{kvp.Key}]",
this, GPALObjectType.GPALExcel, ex);
1444 foreach (var targetPath
in targetPaths)
1448 using var targetWorkbook =
new XLWorkbook();
1449 foreach (var worksheet
in kvp.Value.Worksheets)
1451 var targetWorksheet = targetWorkbook.Worksheets.Add(worksheet.Name);
1452 ExcelHelper.CopyWorksheet(worksheet, targetWorksheet);
1454 targetWorkbook.SaveAs(targetPath);
1455 GPAL.
PublishSimpleEvent(GPALEventType.INFO, $
"Saved unmatched workbook [{kvp.Key}] to [{targetPath}]",
this, GPALObjectType.GPALExcel);
1457 catch (Exception ex)
1459 GPAL.
PublishSimpleEvent(GPALEventType.ERROR, $
"Failed to save unmatched workbook [{kvp.Key}] to [{targetPath}]",
this, GPALObjectType.GPALExcel, ex);
1464 catch (Exception ex)
1466 GPAL.
PublishSimpleEvent(GPALEventType.ERROR, $
"Failed to process workbook [{kvp.Key}]",
this, GPALObjectType.GPALExcel, ex);
1471 catch (Exception ex)
1473 GPAL.
PublishSimpleEvent(GPALEventType.ERROR, $
"Failed to resolve save paths for [{string.Join(",
", gpalFile.Filenames)}]",
this, GPALObjectType.GPALExcel, ex);
1489 GPALEventType.ERROR,
1490 "Grid cannot be null.",
1492 GPALObjectType.GPALExcel);
1496 if (!_workbooks.Any() && _filePaths.Any())
1498 foreach (var path
in _filePaths)
1501 if (!_rangesData.Any())
1504 GPALEventType.ERROR,
1505 "No data to save to grid",
1507 GPALObjectType.GPALExcel);
1511 _operationPerformed =
true;
1515 $
"Saving [{_rangesData.Sum(rangeData => rangeData.Data.Count())}] rows from [{_rangesData.Count}] ranges to grid.",
1517 GPALObjectType.GPALExcel);
1521 foreach (var rangeData
in _rangesData)
1523 foreach (var row
in rangeData.Data)
1527 catch (Exception ex)
1530 GPALEventType.ERROR,
1531 $
"Failed to save to grid",
1533 GPALObjectType.GPALExcel, ex);
1550 if (!_workbooks.Any() && _filePaths.Any())
1552 foreach (var path
in _filePaths)
1555 if (!_rangesData.Any())
1558 GPALEventType.ERROR,
1559 $
"No data to write to sheet [{sheetName}]",
1561 GPALObjectType.GPALExcel);
1563 else if (
string.IsNullOrEmpty(sheetName))
1566 GPALEventType.ERROR,
1567 "Sheet name cannot be empty",
1569 GPALObjectType.GPALExcel);
1573 _operationPerformed =
true;
1577 $
"Saving [{_rangesData.Count}] ranges to sheet [{sheetName}] of [{_workbooks.Count}] workbooks.",
1579 GPALObjectType.GPALExcel);
1581 foreach (var kvp
in _workbooks)
1585 var worksheet = kvp.Value.Worksheets.Any(ws => ws.Name.Equals(sheetName, StringComparison.OrdinalIgnoreCase))
1586 ? kvp.Value.Worksheet(sheetName)
1587 : kvp.Value.Worksheets.Add(sheetName);
1589 if (!
string.IsNullOrEmpty(_currentCell))
1591 target = _currentCell;
1592 worksheet.Cell(target).SetValue(_rangesData.Last().Data.SelectMany(row => row).FirstOrDefault() ??
"");
1596 target = _rangesData.Last().Range;
1597 foreach (var rangeData
in _rangesData)
1599 ExcelHelper.WriteRange(worksheet, rangeData.Range, rangeData.Data);
1603 catch (Exception ex)
1606 GPALEventType.ERROR,
1607 $
"Failed to write to sheet [{sheetName}] in [{kvp.Key}]",
1609 GPALObjectType.GPALExcel, ex);
1626 if (!_workbooks.Any() && _filePaths.Any())
1628 foreach (var path
in _filePaths)
1631 if (!_rangesData.Any())
1634 GPALEventType.ERROR,
1635 $
"No data to write to sheet index [{sheetIndex}]",
1637 GPALObjectType.GPALExcel);
1639 else if (sheetIndex < 1)
1642 GPALEventType.ERROR,
1643 $
"Invalid sheet index [{sheetIndex}]",
1645 GPALObjectType.GPALExcel);
1649 _operationPerformed =
true;
1653 $
"Saving [{_rangesData.Count}] ranges to sheet index [{sheetIndex}] of [{_workbooks.Count}] workbooks.",
1655 GPALObjectType.GPALExcel);
1657 foreach (var kvp
in _workbooks)
1661 var worksheet = kvp.Value.Worksheets.ElementAtOrDefault(sheetIndex - 1) ?? kvp.Value.Worksheets.Add($
"Sheet{sheetIndex}");
1663 if (!
string.IsNullOrEmpty(_currentCell))
1665 target = _currentCell;
1666 worksheet.Cell(target).SetValue(_rangesData.Last().Data.SelectMany(row => row).FirstOrDefault() ??
"");
1670 target = _rangesData.Last().Range;
1671 foreach (var rangeData
in _rangesData)
1673 ExcelHelper.WriteRange(worksheet, rangeData.Range, rangeData.Data);
1677 catch (Exception ex)
1680 GPALEventType.ERROR,
1681 $
"Failed to write to sheet index [{sheetIndex}] in [{kvp.Key}]",
1683 GPALObjectType.GPALExcel, ex);
1702 $
"GPALExcel instance already closed [{_gpalFile?.Filenames?.FirstOrDefault() ?? "unknown
"}]",
1704 GPALObjectType.GPALExcel);
1708 _operationPerformed =
false;
1710 foreach (var kvp
in _workbooks)
1716 kvp.Value.SaveAs(kvp.Key);
1718 kvp.Value.Dispose();
1720 catch (Exception ex)
1723 GPALEventType.ERROR,
1724 $
"Failed to close workbook [{kvp.Key}]",
1726 GPALObjectType.GPALExcel, ex);
1731 _rangesData.Clear();
1732 _currentSheetName =
null;
1733 _currentSheetIndex = -1;
1734 _insertPosition = 0;
1735 _insertSeparator =
" ";
1736 _currentCell =
null;
1748 private IXLWorksheet GetWorksheet(XLWorkbook workbook)
1750 if (!
string.IsNullOrEmpty(_currentSheetName))
1752 return workbook.Worksheets.FirstOrDefault(ws => ws.Name.Equals(_currentSheetName, StringComparison.OrdinalIgnoreCase));
1754 if (-1 != _currentSheetIndex)
1756 return workbook.Worksheets.ElementAtOrDefault(_currentSheetIndex);
1769 internal static IXLWorksheet GetWorksheet(XLWorkbook workbook,
string sheetIdentifier)
1773 if (workbook.TryGetWorksheet(sheetIdentifier, out IXLWorksheet worksheet))
1778 if (
int.TryParse(sheetIdentifier, out
int sheetIndex) && sheetIndex > 0)
1782 worksheet = workbook.Worksheet(sheetIndex);
1790 GPAL.PublishSimpleEvent(Enums.GPALEventType.ERROR, $
"Worksheet [{sheetIdentifier}] not found in workbook and no default name provided.");
1793 catch (Exception ex)
1795 GPAL.PublishSimpleEvent(Enums.GPALEventType.EXCEPTION, $
"Failed to get worksheet [{sheetIdentifier}]",
null, Enums.GPALObjectType.None, ex);
1806 internal static IXLWorksheet GetWorksheet(XLWorkbook workbook,
int sheetIndex)
1810 if (
null != workbook.Worksheet(sheetIndex))
1811 return workbook.Worksheet(sheetIndex);
1813 GPAL.PublishSimpleEvent(Enums.GPALEventType.ERROR, $
"Worksheet [{sheetIndex}] not found in workbook and no default name provided.");
1816 catch (Exception ex)
1818 GPAL.PublishSimpleEvent(Enums.GPALEventType.EXCEPTION, $
"Failed to get worksheet [{sheetIndex}]",
null, Enums.GPALObjectType.None, ex);
IAllowExcelOperations WriteRange(string range)
Writes the range data previously read via WithRange(string) (or another data-producing operation) to ...
IAllowExcelOperations ClearRanges()
Clears any range data read via WithRange(string), WithColumn(string), or WithRowNumber(int),...
IAllowExcelSearchAndReplaceSettings WithSearchValue(string value)
Sets the value to search for in subsequent ReplaceWith(string) operations.
IAllowExcelOperations SaveTo(int sheetIndex)
Writes the previously read range data into the sheet at the given 1-based index of every loaded workb...
IAllowExcelSheetSelection WithFile(GPALFile gpalFile)
Resets this instance and loads the workbook(s) matching gpalFile 's filenames (which may include wild...
IAllowExcelOperations CompareToRange(string range)
Compares each previously read range against range on the currently selected sheet of every loaded wo...
IAllowExcelOperations CalculateCount(out string result)
Counts every non-empty value across all previously read range data.
IAllowExcelOperations CompareToFile(GPALFile gpalFile)
Compares each previously read range against the same range/sheet in the workbook(s) matching gpalFile...
IAllowExcelOperations InsertValue(string value)
Inserts value into the cell selected via WithCell(string) on every loaded workbook,...
IAllowExcelOperations SaveTo(IGPALGrid< string > grid)
Appends every row from the previously read range data into grid .
IAllowExcelOperations SetValue(string value)
Sets the value of the cell selected via WithCell(string) on every loaded workbook,...
IAllowExcelOperations WithSheet(int sheetIndex)
Selects the sheet at the given 1-based index for subsequent Excel operations on every loaded workbook...
void Close(bool saveOnClose)
Closes every loaded workbook, optionally saving each back to its source path first,...
IAllowExcelOperations SaveTo(GPALFile gpalFile)
Saves the loaded workbook(s) to the file(s) matching gpalFile 's filenames (which may include wildcar...
IGPALExcel ToGPALObject()
Returns this instance as an IGPALExcel, completing the fluent configuration chain.
IAllowExcelOperations WithRange(string range)
Reads the given cell range from the currently selected sheet of every loaded workbook and stores the ...
IAllowExcelOperations ReplaceWith(string value)
Replaces every occurrence of the value set via WithSearchValue(string) with value ,...
IAllowExcelCellSettings WithInsertSeparator(string separator)
Sets the separator that InsertValue(string) places between the inserted value and the cell's existing...
IAllowExcelOperations GetCompareResults(out IGPALGrid< string > results)
Returns the cell-level differences accumulated by the CompareTo* methods (CompareToGrid(IGPALGrid<str...
IAllowExcelOperations AppendValue(string value)
Appends value to the end of the existing content of the cell selected via WithCell(string) on every ...
IAllowExcelCellSettings WithInsertPosition(int position)
Sets where InsertValue(string) places its value relative to the current cell content: 0 inserts befor...
IAllowExcelCellSettings WithCell(string cell)
Selects a single cell address (e.g. "B3") on the currently selected sheet as the target for subsequen...
IAllowExcelOperations WithRowNumber(int rowNumber)
Reads every value in the given row from the currently selected sheet of the first loaded workbook tha...
IAllowExcelOperations CompareToGrid(IGPALGrid< string > grid)
Compares each previously read range against grid , recording any cell-level differences for retrieval...
IAllowExcelOperations WithSheet(string sheetName)
Selects the sheet with the given name (case-insensitive) for subsequent Excel operations on every loa...
IAllowExcelOperations WithColumn(string column)
Reads every value in the given column from the currently selected sheet of the first loaded workbook ...
IAllowExcelOperations SaveTo(string sheetName)
Writes the previously read range data into the sheet named sheetName of every loaded workbook,...
IAllowExcelOperations CalculateSum(out string result)
Sums every numeric value across all previously read range data (non-numeric values are ignored).
IAllowExcelOperations PrependValue(string value)
Prepends value to the beginning of the existing content of the cell selected via WithCell(string) on...
GPAL File object instantied with GPAL.File Used to load tokens into a GPALGrid [rows/columns].
List< string > Filenames
Get the list of filenames.
Everything starts here, all the GPAL controls and global settings using fluent syntax are here....
static void PublishSimpleEvent(GPALEventType gPALEventType, string msg, dynamic gPALObject=null, Enums.GPALObjectType gPALObjectType=GPALObjectType.None, Exception ex=null)
Publish a message to either the information channel or exception channel (if exception passed in) Pub...