// Copyright (c) 2022- schick Informatik // Description: Compares excel files and highlights changes // using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using Microsoft.Office.Interop.Excel; namespace ENI2.Excel { /// /// Diese Klasse beinhaltet den von Anmeldungen unabhängigen Vergleich von Excel Sheets. Damit /// können dann Updates von "außen" einfacher abgearbeitet werden. Zellen und sheets werden bei /// Aktualisierung bunt eingefärbt /// public static class ExcelComparer { private static int diffColor = ColorTranslator.ToOle(Color.FromArgb(150, 150, 255)); // blue private static bool GetSheetRange(Worksheet sheet, out int lastUsedRow, out int lastUsedColumn) { try { Range last = sheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing); Range range = sheet.get_Range("A1", last); lastUsedRow = last.Row; lastUsedColumn = last.Column; return true; } catch(Exception) { lastUsedColumn = 0; lastUsedRow = 0; return false; } } public static string Compare(string sourcePath, string targetPath, out string errorMessage) { string fileName = Path.GetTempPath() + Guid.NewGuid().ToString() + ".xlsx"; errorMessage = ""; int counter = 0; try { File.Copy(targetPath, fileName); ExcelReader source = new ExcelReader(sourcePath); ExcelReader comparison = new ExcelReader(fileName, false); /* // loop through named cells foreach (string name in comparison.NameDict.Keys) { if (!source.NameDict.ContainsKey(name)) continue; string sourceText = source.ReadText(name); string targetText = comparison.ReadText(name); if (sourceText == null) { if (targetText != null) { comparison.Colorize(name, diffColor); counter++; } } else if (targetText == null) { if (sourceText != null) { comparison.Colorize(name, diffColor); counter++; } } else if ((sourceText != null) && (targetText != null)) { if (!sourceText.Equals(targetText)) { // turn cell blue comparison.Colorize(name, diffColor); counter++; } } } */ comparison.Save(fileName); errorMessage = string.Format("{0} differences found", counter); } catch (Exception ex) { errorMessage = ex.Message; } return fileName; } } }