新增 SOP 步骤 Excel 导出

This commit is contained in:
wanglei 2026-11-28 16:27:51 +08:00
parent 2a424cd651
commit 79037a0e40
6 changed files with 128 additions and 3 deletions

View File

@ -20,6 +20,8 @@
<PackageReference Include="Prism.DryIoc.Avalonia" Version="9.0.537.11130" />
<PackageReference Include="Avalonia.Desktop" Version="12.1.5" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="12.1.5" />
<PackageReference Include="ClosedXML" Version="0.105.1" />
<InternalsVisibleTo Include="VideoFlowTest.Smoke" />
<AvaloniaResource Include="Assets/**" />
<AvaloniaResource Include="BWS.ico" />
<Content Include="Assets/bws.svg" CopyToOutputDirectory="PreserveNewest" />

View File

@ -118,6 +118,8 @@
<WrapPanel Orientation="Horizontal" IsEnabled="{Binding CanTransferSteps}">
<Button Content="导入步骤" Click="ImportStepsFile" ToolTip.Tip="从步骤文件或完整配方导入,可选择追加或替换" />
<Button Content="导出步骤" Click="ExportStepsFile" ToolTip.Tip="导出全部步骤及关联区域,保留触发、AI判定与复检设置" />
<!-- 供现场查阅的 Excel 文件包含步骤文字和已保存的关键帧。 -->
<Button Content="导出SOP文件" Click="ExportSopFile" ToolTip.Tip="将步骤和关键帧导出为 Excel 文件" />
</WrapPanel>
<TextBlock Text="{Binding StepTransferStatus}" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
</StackPanel>

View File

@ -0,0 +1,67 @@
using System.IO;
using ClosedXML.Excel;
namespace SopHelper.VVMs.RecipeEditor;
/// <summary>供 SOP 表格导出线程读取的步骤快照。</summary>
internal sealed record SopExcelRow(int Id, string Name, string Description, string KeyFrameBase64);
/// <summary>生成供查阅的 SOP 工作簿,并在生成成功后替换目标文件。</summary>
internal static class SopExcelExport
{
/// <summary>将步骤按执行顺序写入指定路径,关键帧随工作簿保存。</summary>
public static void Save(string path, IReadOnlyList<SopExcelRow> steps)
{
using var workbook = new XLWorkbook();
var sheet = workbook.AddWorksheet("SOP");
sheet.Cell("A1").Value = "步骤号";
sheet.Cell("B1").Value = "步骤名";
sheet.Cell("C1").Value = "步骤说明";
sheet.Cell("D1").Value = "关键帧";
var header = sheet.Range("A1:D1");
header.Style.Font.Bold = true;
header.Style.Fill.BackgroundColor = XLColor.LightBlue;
sheet.SheetView.FreezeRows(1);
sheet.Column(1).Width = 12;
sheet.Column(2).Width = 28;
sheet.Column(3).Width = 65;
sheet.Column(4).Width = 42;
sheet.Columns(2, 3).Style.Alignment.WrapText = true;
sheet.Columns(1, 4).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
var row = 2;
foreach (var step in steps.OrderBy(step => step.Id))
{
sheet.Cell(row, 1).Value = step.Id;
sheet.Cell(row, 2).Value = step.Name;
sheet.Cell(row, 3).Value = step.Description;
sheet.Row(row).AdjustToContents(2, 3);
if (!string.IsNullOrWhiteSpace(step.KeyFrameBase64))
{
// 以原图比例限制显示尺寸,按 96 DPI 将图片高度换算成工作表行高。
using var image = new MemoryStream(Convert.FromBase64String(step.KeyFrameBase64));
var picture = sheet.AddPicture(image);
var scale = Math.Min(1, Math.Min(260.0 / picture.Width, 150.0 / picture.Height));
var width = Math.Max(1, (int)Math.Round(picture.Width * scale));
var height = Math.Max(1, (int)Math.Round(picture.Height * scale));
picture.MoveTo(sheet.Cell(row, 4), 4, 4).WithSize(width, height);
sheet.Row(row).Height = Math.Max(sheet.Row(row).Height, (height + 8) * .75);
}
row++;
}
// 在目标目录写临时文件,避免生成失败时截断已有工作簿。
var temporary = Path.Combine(Path.GetDirectoryName(path)!, $".sop-export-{Guid.NewGuid():N}.tmp");
try
{
using (var stream = File.Create(temporary))
workbook.SaveAs(stream);
File.Move(temporary, path, overwrite: true);
}
finally
{
try { File.Delete(temporary); }
catch (Exception error) when (error is IOException or UnauthorizedAccessException) { }
}
}
}

View File

@ -1,4 +1,4 @@
// 编辑器的步骤交换视图部分:处理文件导入/导出、追加或替换选择以及导入结果提示。
// 编辑器的步骤交换视图部分:处理步骤交换与 SOP 表格的文件选择、结果提示。
using Avalonia.Controls;
using Avalonia.Interactivity;
@ -67,6 +67,35 @@ public partial class RecipeEditor
}
}
/// <summary>选择 Excel 保存位置并导出当前编辑中的步骤,与步骤交换共用防重入门控。</summary>
private async void ExportSopFile(object? sender, RoutedEventArgs args)
{
if (_stepTransferInProgress || _model is not { CanTransferSteps: true } model || TopLevel.GetTopLevel(this) is not Window owner) return;
_stepTransferInProgress = true;
try
{
var name = string.Concat(model.Recipe.Name.Select(c => Path.GetInvalidFileNameChars().Contains(c) ? '_' : c));
var file = await owner.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
{
Title = "导出SOP文件", SuggestedFileName = name + ".xlsx", DefaultExtension = "xlsx", ShowOverwritePrompt = true,
FileTypeChoices = [new("Excel 工作簿") { Patterns = ["*.xlsx"] }]
});
if (file is null || _closing || !ReferenceEquals(model, _model) || !model.CanTransferSteps) return;
var path = file.TryGetLocalPath() ?? throw new IOException("请选择本地保存位置");
if (!Path.GetExtension(path).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
throw new IOException("请使用 .xlsx 文件扩展名");
if (model.IsCurrentRecipeFile(path)) throw new IOException("SOP 导出不能覆盖当前配方文件");
// 在 UI 线程固定步骤数据,后台写文件时不再访问可编辑节点。
var steps = model.Recipe.Steps.Select(step => new SopExcelRow(step.Id, step.Name, step.Description, step.KeyFrameBase64)).ToArray();
await Task.Run(() => SopExcelExport.Save(path, steps));
if (!_closing && ReferenceEquals(model, _model))
model.StepTransferStatus = $"已导出 {steps.Length} 个步骤到 Excel:{Path.GetFileName(path)}";
}
catch (Exception error) { await ShowNotice("导出SOP文件失败", error.Message, false); }
finally { _stepTransferInProgress = false; }
}
private async Task<string?> ChooseStepImportMode(int incoming, int current)
{
if (_closing || _dialog is not null || TopLevel.GetTopLevel(this) is not Window owner) return null;

View File

@ -34,6 +34,8 @@ internal static class Program
if (args.Contains("--live")) { LiveVideoFlowChecks.Run(args); return; }
if (args.Contains("--agent-generation-only")) { AgentDraftGenerationChecks.Run(root); return; }
if (args.Contains("--optimization-only")) { OptimizeStepsChecks.Run(); return; }
// 单独验证步骤交换和 Excel 导出,无需先执行视频判定用例。
if (args.Contains("--step-transfer-only")) { StepTransferChecks.Run(root); return; }
CheckLegacyRecipeRoundTrip();
// 单独验证标准视频链路,便于定位回放与流程回测问题。
if (args.Contains("--standard-video-only"))

View File

@ -1,6 +1,7 @@
using System.Text.Json;
using Avalonia.Controls;
using Avalonia.VisualTree;
using ClosedXML.Excel;
using Prism.Dialogs;
using SopHelper.Engine.Sop;
using SopHelper.VVMs.RecipeEditor;
@ -61,8 +62,11 @@ internal static class StepTransferChecks
var window = new Window { Content = rendered, Width = 1040, Height = 900 }; window.Show(); window.UpdateLayout();
var tabs = rendered.GetVisualDescendants().OfType<TabControl>().Single();
tabs.SelectedItem = tabs.Items.OfType<TabItem>().Single(t => t.Header?.ToString() == "步骤"); window.UpdateLayout();
Check(rendered.GetVisualDescendants().OfType<Button>().Any(b => b.Content?.ToString() == "导入步骤")
&& rendered.GetVisualDescendants().OfType<Button>().Any(b => b.Content?.ToString() == "导出步骤"), "步骤页显示导入和导出入口");
var toolbar = rendered.GetVisualDescendants().OfType<WrapPanel>().Single(panel =>
panel.Children.OfType<Button>().Any(button => button.Content?.ToString() == "导出步骤"));
Check(toolbar.Children.OfType<Button>().Select(button => button.Content?.ToString())
.SequenceEqual(new[] { "导入步骤", "导出步骤", "导出SOP文件" }), "SOP 导出入口紧跟步骤导出");
CheckSopExcel(root);
var edited = model.Recipe.ToConfig();
var exported = SopStepTransfer.Read(model.ExportStepsText());
Check(JsonSerializer.Serialize(edited.Sop.Steps) == JsonSerializer.Serialize(exported.Sop.Steps), "界面导入后再次导出须保留全部步骤配置");
@ -80,5 +84,24 @@ internal static class StepTransferChecks
window.Close(); model.OnDialogClosed();
Console.WriteLine("PASS: 步骤导入导出全字段往返、追加替换、区域冲突映射、全局设置隔离、非法输入原子保护及界面入口");
}
/// <summary>重新打开生成的工作簿,验证列、文字类型和关键帧行的对应关系。</summary>
private static void CheckSopExcel(string root)
{
const string png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aXuoAAAAASUVORK5CYII=";
Directory.CreateDirectory(root);
var path = Path.Combine(root, "sop-export.xlsx");
SopExcelExport.Save(path, [new(8, "确认", "第一行\n第二行", png), new(2, "=定位", "说明", "")]);
using var workbook = new XLWorkbook(path);
var sheet = workbook.Worksheet("SOP");
Check(sheet.Range("A1:D1").Cells().Select(cell => cell.GetString())
.SequenceEqual(new[] { "步骤号", "步骤名", "步骤说明", "关键帧" }), "Excel 导出须包含四个指定字段");
Check(sheet.Cell("A2").GetValue<int>() == 2 && sheet.Cell("A3").GetValue<int>() == 8
&& sheet.Cell("B2").GetString() == "=定位" && !sheet.Cell("B2").HasFormula
&& sheet.Cell("C3").GetString() == "第一行\n第二行", "步骤按编号排列且保留原始文本");
var picture = sheet.Pictures.Single();
Check(picture.TopLeftCell.Address.RowNumber == 3 && picture.TopLeftCell.Address.ColumnNumber == 4, "关键帧内嵌在对应步骤的第四列");
Console.WriteLine("PASS: SOP Excel 四列、步骤顺序、文本及关键帧");
}
private static void Check(bool value, string message) { if (!value) throw new Exception(message); }
}