using ClosedXML.Excel; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics.CodeAnalysis; using System.IO; using System.IO.Packaging; using System.Linq; using System.Text.RegularExpressions; namespace Strata.ContinuousImprovement.Biz.Test.Unit.Utilities { [ExcludeFromCodeCoverage] internal static class ExcelDocsComparer { public static bool Compare(string left, string right, out string message) { using (FileStream leftStream = File.OpenRead(left)) using (FileStream rightStream = File.OpenRead(right)) { return Compare(leftStream, rightStream, out message); } } public static bool Compare(this Stream result, Stream expected, out string message) { using (Package leftPackage = Package.Open(result, FileMode.Open, FileAccess.Read)) using (Package rightPackage = Package.Open(expected, FileMode.Open, FileAccess.Read)) { return PackageHelper.Compare(leftPackage, rightPackage, false, ExcludeMethod, out message); } } public static bool Compare(this IXLWorkbook result, IXLWorkbook expected, out string message) { using (var resultStream = new MemoryStream()) using (var wbStream = new MemoryStream()) { expected.SaveAs(wbStream); result.SaveAs(resultStream); return wbStream.Compare(resultStream, out message); } } private static bool ExcludeMethod(Uri uri) { //Exclude service data if (uri.OriginalString.EndsWith(".rels") || uri.OriginalString.EndsWith(".psmdcp")) { return true; } return false; } public static Dictionary GetDataTables(this IXLWorkbook workbook) { var dataTables = new Dictionary(); foreach (var ws in workbook.Worksheets) { var name = ws.Name; DataTable dt = new DataTable(); foreach (var cell in ws.RowsUsed().First().CellsUsed()) { var columnName = "_" + cell.Value.ToString().ToAlphaNumericOnly(); dt.Columns.Add(columnName); } foreach (var row in ws.RowsUsed().Where(x => x.RowNumber() > 1)) { DataRow temprow = dt.NewRow(); for (int i = 0; i < dt.Columns.Count; i++) { try { var cellValue = row.Cells().ElementAt(i).Value.ToString(); temprow[i] = cellValue.TrimWhiteSpaces().RemoveLineBreaks(); } catch (Exception) { // Empty Cell } } dt.Rows.Add(temprow); } dataTables.Add(name, dt); } return dataTables; } private static string ToAlphaNumericOnly(this string input) { Regex rgx = new Regex("[^a-zA-Z0-9]"); return rgx.Replace(input, ""); } public static string TrimWhiteSpaces(this string text) { text = text.TrimStart(' '); text = text.TrimEnd(' '); text = text.Trim(); return text; } public static string RemoveLineBreaks(this string text) { string replaceWith = ""; string removedBreaks = text.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith); return text; } } }