feat: 优化界面布局及样式

This commit is contained in:
chenshoulin
2026-11-19 00:58:05 +08:00
parent 1e3504707a
commit 3f02f4c704
14 changed files with 4000 additions and 120 deletions
+160
View File
@@ -0,0 +1,160 @@
using System;
using System.Collections.Generic;
namespace DataCompare.Core
{
public static class ColumnMapper
{
public static List<ColumnMapping> ByName(
IList<ColumnInfo> left,
IList<ColumnInfo> right,
IList<string> keys,
out string missingKeys)
{
var mappings = new List<ColumnMapping>();
var missing = new List<string>();
var keyNames = keys ?? new string[0];
if (left != null)
{
for (int i = 0; i < left.Count; i++)
{
var leftColumn = left[i];
if (leftColumn == null || string.IsNullOrWhiteSpace(leftColumn.Name))
continue;
var rightColumn = Find(right, leftColumn.Name);
if (rightColumn == null)
continue;
mappings.Add(new ColumnMapping
{
LeftColumn = leftColumn.Name,
RightColumn = rightColumn.Name,
IsKey = Contains(keyNames, leftColumn.Name),
Compare = true
});
}
}
for (int i = 0; i < keyNames.Count; i++)
{
var key = (keyNames[i] ?? "").Trim();
if (key.Length == 0 || Listed(missing, key))
continue;
if (Find(left, key) == null || Find(right, key) == null)
missing.Add(key);
}
missingKeys = missing.Count == 0 ? "" : "缺少键列:" + string.Join(",", missing);
return mappings;
}
public static string GuessKey(IList<ColumnMapping> mappings)
{
if (mappings == null)
return null;
string exact = null;
string suffix = null;
int suffixCount = 0;
for (int i = 0; i < mappings.Count; i++)
{
var name = mappings[i] == null ? null : mappings[i].LeftColumn;
if (string.IsNullOrWhiteSpace(name))
continue;
if (string.Equals(name, "id", StringComparison.OrdinalIgnoreCase))
{
if (exact == null)
exact = name;
continue;
}
if (name.Length > 2 && name.EndsWith("id", StringComparison.OrdinalIgnoreCase))
{
suffixCount++;
suffix = name;
}
}
if (exact != null)
return exact;
if (suffixCount == 1)
return suffix;
return null;
}
public static string KeyHint(IList<ColumnMapping> mappings)
{
var names = new List<string>();
if (mappings != null)
{
for (int i = 0; i < mappings.Count; i++)
{
var name = mappings[i] == null ? null : mappings[i].LeftColumn;
if (string.IsNullOrWhiteSpace(name))
continue;
if (string.Equals(name, "id", StringComparison.OrdinalIgnoreCase)
|| (name.Length > 2 && name.EndsWith("id", StringComparison.OrdinalIgnoreCase)))
names.Add(name);
}
}
if (names.Count == 0)
return "请在字段表中勾选「键」。";
if (names.Count == 1)
return "可勾选「" + names[0] + "」作为键。";
return "可选键列:" + string.Join("、", names) + "。请勾选其中一个。";
}
public static void MarkKey(IList<ColumnMapping> mappings, string leftName)
{
if (mappings == null || string.IsNullOrWhiteSpace(leftName))
return;
for (int i = 0; i < mappings.Count; i++)
{
if (mappings[i] != null && string.Equals(mappings[i].LeftColumn, leftName, StringComparison.OrdinalIgnoreCase))
mappings[i].IsKey = true;
}
}
public static bool HasKey(IList<ColumnMapping> mappings)
{
if (mappings == null)
return false;
for (int i = 0; i < mappings.Count; i++)
{
var mapping = mappings[i];
if (mapping != null
&& mapping.IsKey
&& !string.IsNullOrWhiteSpace(mapping.LeftColumn)
&& !string.IsNullOrWhiteSpace(mapping.RightColumn))
return true;
}
return false;
}
static ColumnInfo Find(IList<ColumnInfo> columns, string name)
{
if (columns == null || string.IsNullOrWhiteSpace(name))
return null;
for (int i = 0; i < columns.Count; i++)
{
if (columns[i] != null && string.Equals(columns[i].Name, name, StringComparison.OrdinalIgnoreCase))
return columns[i];
}
return null;
}
static bool Contains(IList<string> names, string name)
{
for (int i = 0; i < names.Count; i++)
{
if (string.Equals((names[i] ?? "").Trim(), name, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
static bool Listed(List<string> names, string name)
{
for (int i = 0; i < names.Count; i++)
{
if (string.Equals(names[i], name, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
}
}
+187
View File
@@ -0,0 +1,187 @@
using System.Collections.Generic;
namespace DataCompare.Core
{
public sealed class ExportTable
{
public string SheetTitle { get; set; }
public string Label { get; set; }
public string Status { get; set; }
public string Note { get; set; }
public CompareResult Result { get; set; }
public bool Completed { get; set; }
}
public sealed class XlsxSheet
{
public string Name;
public readonly List<string[]> Rows = new List<string[]>();
}
public static class DiffWorkbook
{
public const int MaxRows = 1048576;
public static bool Include(RowDiff diff, int filter)
{
if (diff == null)
return false;
switch (filter)
{
case 1: return diff.Status == DiffStatus.LeftOnly;
case 2: return diff.Status == DiffStatus.RightOnly;
case 3: return diff.Status == DiffStatus.Different;
case 4: return diff.Status == DiffStatus.DuplicateKey || diff.Status == DiffStatus.InvalidKey;
default: return true;
}
}
public static List<XlsxSheet> Build(IList<ExportTable> tables, int filter)
{
return Build(tables, filter, MaxRows);
}
public static List<XlsxSheet> Build(IList<ExportTable> tables, int filter, int maxRows)
{
if (maxRows < 2)
maxRows = 2;
var sheets = new List<XlsxSheet>();
var used = new List<string>();
var summary = Begin(used, "汇总");
summary.Rows.Add(new[]
{
"表", "状态", "左侧行数", "右侧行数", "相同", "仅左", "仅右", "内容不同", "键重复", "键无效", "说明"
});
if (tables != null)
{
for (int i = 0; i < tables.Count; i++)
{
var table = tables[i];
if (table == null)
continue;
if (summary.Rows.Count >= maxRows)
{
sheets.Add(summary);
summary = Begin(used, "汇总");
summary.Rows.Add(new[]
{
"表", "状态", "左侧行数", "右侧行数", "相同", "仅左", "仅右", "内容不同", "键重复", "键无效", "说明"
});
}
summary.Rows.Add(SummaryRow(table));
}
}
sheets.Add(summary);
if (tables != null)
{
for (int i = 0; i < tables.Count; i++)
{
var table = tables[i];
if (table == null || !table.Completed || table.Result == null)
continue;
var sheet = Begin(used, table.SheetTitle);
sheet.Rows.Add(DiffHeader());
var diffs = table.Result.Diffs;
if (diffs != null)
{
for (int d = 0; d < diffs.Length; d++)
{
if (!Include(diffs[d], filter))
continue;
AddDiff(sheets, used, ref sheet, table.SheetTitle, diffs[d], maxRows);
}
}
sheets.Add(sheet);
}
}
return sheets;
}
static void AddDiff(
List<XlsxSheet> sheets,
List<string> used,
ref XlsxSheet sheet,
string title,
RowDiff diff,
int maxRows)
{
if (diff.Cells == null || diff.Cells.Length == 0)
{
sheet = Room(sheets, used, sheet, title, maxRows);
sheet.Rows.Add(new[]
{
Text(diff.StatusText), Text(diff.KeyText), Text(diff.Summary), "", "", "", ""
});
return;
}
for (int c = 0; c < diff.Cells.Length; c++)
{
var cell = diff.Cells[c];
sheet = Room(sheets, used, sheet, title, maxRows);
if (cell == null)
{
sheet.Rows.Add(new[]
{
Text(diff.StatusText), Text(diff.KeyText), Text(diff.Summary), "", "", "", ""
});
continue;
}
sheet.Rows.Add(new[]
{
Text(diff.StatusText),
Text(diff.KeyText),
Text(diff.Summary),
Text(cell.ColumnName),
Text(cell.LeftText),
Text(cell.RightText),
cell.IsDifferent ? "是" : "否"
});
}
}
static XlsxSheet Room(List<XlsxSheet> sheets, List<string> used, XlsxSheet sheet, string title, int maxRows)
{
if (sheet.Rows.Count < maxRows)
return sheet;
sheets.Add(sheet);
var next = Begin(used, title);
next.Rows.Add(DiffHeader());
return next;
}
static string[] DiffHeader()
{
return new[] { "状态", "键", "摘要", "列", "左侧", "右侧", "是否不同" };
}
static string[] SummaryRow(ExportTable table)
{
var result = table.Completed ? table.Result : null;
return new[]
{
Text(table.Label),
Text(table.Status),
result == null ? "" : result.LeftRowCount.ToString(),
result == null ? "" : result.RightRowCount.ToString(),
result == null ? "" : result.MatchedCount.ToString(),
result == null ? "" : result.LeftOnlyCount.ToString(),
result == null ? "" : result.RightOnlyCount.ToString(),
result == null ? "" : result.DifferentCount.ToString(),
result == null ? "" : result.DuplicateCount.ToString(),
result == null ? "" : result.InvalidCount.ToString(),
Text(table.Note)
};
}
static XlsxSheet Begin(List<string> used, string title)
{
return new XlsxSheet { Name = SheetNames.Make(title, used) };
}
static string Text(string value)
{
return value ?? "";
}
}
}
+63
View File
@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
namespace DataCompare.Core
{
public static class SheetNames
{
public static string Make(string name, ICollection<string> used)
{
var clean = Clean(name);
if (used == null)
return clean;
var unique = clean;
if (Contains(used, unique))
{
for (int n = 2; n < 10000; n++)
{
var suffix = "_" + n.ToString();
var headLength = 31 - suffix.Length;
if (headLength < 1)
headLength = 1;
var head = clean.Length <= headLength ? clean : clean.Substring(0, headLength);
unique = head + suffix;
if (!Contains(used, unique))
break;
}
}
used.Add(unique);
return unique;
}
public static string Clean(string name)
{
if (string.IsNullOrWhiteSpace(name))
name = "表";
var chars = name.Trim().ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
if (c < ' ' || c == '\\' || c == '/' || c == '?' || c == '*' || c == '[' || c == ']' || c == ':')
chars[i] = '_';
}
var text = new string(chars).Trim().Trim('\'');
if (text.Length == 0)
text = "表";
if (string.Equals(text, "History", StringComparison.OrdinalIgnoreCase))
text = "History_";
if (text.Length > 31)
text = text.Substring(0, 31);
return text;
}
static bool Contains(ICollection<string> used, string name)
{
foreach (var item in used)
{
if (string.Equals(item, name, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
}
}
+108
View File
@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
namespace DataCompare.Core
{
public sealed class TableMatchRule
{
public string Id { get; set; }
public string Name { get; set; }
public bool IgnoreCase { get; set; }
public bool StripSchemaPrefix { get; set; }
public string Separator { get; set; }
public bool NameOnly { get; set; }
public bool IsBuiltIn
{
get { return Id == "same" || Id == "prefix"; }
}
public static TableMatchRule SameName()
{
return new TableMatchRule
{
Id = "same",
Name = "同名",
IgnoreCase = true,
StripSchemaPrefix = false,
Separator = "_",
NameOnly = false
};
}
public static TableMatchRule SchemaPrefix()
{
return new TableMatchRule
{
Id = "prefix",
Name = "模式前缀",
IgnoreCase = true,
StripSchemaPrefix = true,
Separator = "_",
NameOnly = false
};
}
}
public static class TableMatcher
{
public static string Key(TableRef table, TableMatchRule rule)
{
if (table == null)
return "";
if (rule == null)
rule = TableMatchRule.SchemaPrefix();
var schema = SchemaOf(table);
var name = table.Name ?? "";
var separator = string.IsNullOrEmpty(rule.Separator) ? "_" : rule.Separator;
if (rule.IgnoreCase)
{
schema = schema.ToLowerInvariant();
name = name.ToLowerInvariant();
separator = separator.ToLowerInvariant();
}
if (rule.StripSchemaPrefix && schema.Length > 0 && separator.Length > 0)
{
var prefix = schema + separator;
if (name.StartsWith(prefix, StringComparison.Ordinal))
name = name.Substring(prefix.Length);
}
if (rule.NameOnly)
return "\0" + name;
return schema + "\0" + name;
}
public static List<TableRef> Match(TableRef source, IList<TableRef> candidates, TableMatchRule rule)
{
var found = new List<TableRef>();
if (source == null || candidates == null)
return found;
var key = Key(source, rule);
if (key.Length == 0 || key == "\0")
return found;
for (int i = 0; i < candidates.Count; i++)
{
if (string.Equals(Key(candidates[i], rule), key, StringComparison.Ordinal))
found.Add(candidates[i]);
}
return found;
}
public static bool SameTable(TableRef left, TableRef right)
{
if (left == null || right == null)
return false;
return string.Equals(left.Catalog ?? "", right.Catalog ?? "", StringComparison.OrdinalIgnoreCase)
&& string.Equals(left.Schema ?? "", right.Schema ?? "", StringComparison.OrdinalIgnoreCase)
&& string.Equals(left.Name ?? "", right.Name ?? "", StringComparison.OrdinalIgnoreCase);
}
static string SchemaOf(TableRef table)
{
if (!string.IsNullOrEmpty(table.Schema))
return table.Schema;
return table.Catalog ?? "";
}
}
}
+190
View File
@@ -0,0 +1,190 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Xml;
namespace DataCompare.Core
{
public static class XlsxFile
{
const int MaxCell = 32767;
public static void Save(string path, IList<XlsxSheet> sheets)
{
if (string.IsNullOrWhiteSpace(path))
throw new InvalidOperationException("请选择导出文件。");
if (sheets == null || sheets.Count == 0)
throw new InvalidOperationException("没有可写入的工作表。");
var directory = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(directory))
Directory.CreateDirectory(directory);
if (File.Exists(path))
File.Delete(path);
using (var zip = ZipFile.Open(path, ZipArchiveMode.Create))
{
WriteText(zip, "[Content_Types].xml", ContentTypes(sheets.Count));
WriteText(zip, "_rels/.rels",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">"
+ "<Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\" Target=\"xl/workbook.xml\"/>"
+ "</Relationships>");
WriteText(zip, "xl/_rels/workbook.xml.rels", WorkbookRels(sheets.Count));
WriteWorkbook(zip, sheets);
for (int i = 0; i < sheets.Count; i++)
WriteSheet(zip, sheets[i], i + 1);
}
}
static string ContentTypes(int count)
{
var builder = new StringBuilder();
builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
builder.Append("<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">");
builder.Append("<Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>");
builder.Append("<Default Extension=\"xml\" ContentType=\"application/xml\"/>");
builder.Append("<Override PartName=\"/xl/workbook.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml\"/>");
for (int i = 1; i <= count; i++)
{
builder.Append("<Override PartName=\"/xl/worksheets/sheet");
builder.Append(i);
builder.Append(".xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml\"/>");
}
builder.Append("</Types>");
return builder.ToString();
}
static string WorkbookRels(int count)
{
var builder = new StringBuilder();
builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
builder.Append("<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">");
for (int i = 1; i <= count; i++)
{
builder.Append("<Relationship Id=\"rId");
builder.Append(i);
builder.Append("\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet\" Target=\"worksheets/sheet");
builder.Append(i);
builder.Append(".xml\"/>");
}
builder.Append("</Relationships>");
return builder.ToString();
}
static void WriteWorkbook(ZipArchive zip, IList<XlsxSheet> sheets)
{
var entry = zip.CreateEntry("xl/workbook.xml", CompressionLevel.Optimal);
using (var stream = entry.Open())
using (var writer = Xml(stream))
{
writer.WriteStartElement("workbook", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");
writer.WriteAttributeString("xmlns", "r", null, "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
writer.WriteStartElement("sheets");
for (int i = 0; i < sheets.Count; i++)
{
writer.WriteStartElement("sheet");
writer.WriteAttributeString("name", SheetNames.Clean(sheets[i].Name));
writer.WriteAttributeString("sheetId", (i + 1).ToString());
writer.WriteAttributeString("r", "id", "http://schemas.openxmlformats.org/officeDocument/2006/relationships", "rId" + (i + 1));
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndElement();
}
}
static void WriteSheet(ZipArchive zip, XlsxSheet sheet, int index)
{
var entry = zip.CreateEntry("xl/worksheets/sheet" + index + ".xml", CompressionLevel.Optimal);
using (var stream = entry.Open())
using (var writer = Xml(stream))
{
writer.WriteStartElement("worksheet", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");
writer.WriteStartElement("sheetData");
var rows = sheet == null ? null : sheet.Rows;
int count = rows == null ? 0 : rows.Count;
for (int r = 0; r < count; r++)
{
var values = rows[r] ?? new string[0];
writer.WriteStartElement("row");
writer.WriteAttributeString("r", (r + 1).ToString());
for (int c = 0; c < values.Length; c++)
{
writer.WriteStartElement("c");
writer.WriteAttributeString("r", ColumnName(c + 1) + (r + 1));
writer.WriteAttributeString("t", "inlineStr");
writer.WriteStartElement("is");
writer.WriteStartElement("t");
var text = CellText(values[c]);
if (text.Length > 0 && (text[0] == ' ' || text[text.Length - 1] == ' ' || text.IndexOf('\n') >= 0 || text.IndexOf('\r') >= 0))
writer.WriteAttributeString("xml", "space", "http://www.w3.org/XML/1998/namespace", "preserve");
writer.WriteString(text);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndElement();
}
}
static void WriteText(ZipArchive zip, string name, string text)
{
var entry = zip.CreateEntry(name, CompressionLevel.Optimal);
using (var stream = entry.Open())
using (var writer = new StreamWriter(stream, new UTF8Encoding(false)))
writer.Write(text);
}
static XmlWriter Xml(Stream stream)
{
var settings = new XmlWriterSettings
{
Encoding = new UTF8Encoding(false),
OmitXmlDeclaration = false,
CloseOutput = false
};
return XmlWriter.Create(stream, settings);
}
static string ColumnName(int index)
{
var text = "";
while (index > 0)
{
index--;
text = (char)('A' + (index % 26)) + text;
index /= 26;
}
return text;
}
static string CellText(string value)
{
if (string.IsNullOrEmpty(value))
return "";
var builder = new StringBuilder(Math.Min(value.Length, MaxCell));
for (int i = 0; i < value.Length && builder.Length < MaxCell; i++)
{
char c = value[i];
if (char.IsSurrogate(c))
{
if (builder.Length + 2 > MaxCell || i + 1 >= value.Length || !char.IsSurrogatePair(c, value[i + 1]))
continue;
builder.Append(c);
builder.Append(value[i + 1]);
i++;
continue;
}
if (c == '\t' || c == '\n' || c == '\r' || c >= ' ')
builder.Append(c);
}
return builder.ToString();
}
}
}