39 lines
1.5 KiB
C#
39 lines
1.5 KiB
C#
using System.Text.Json;
|
|
using ClosedXML.Excel;
|
|
|
|
namespace Kbx.Tests.Scenarios;
|
|
|
|
/// <summary>Builds an XLSX from the checked-in synthetic JSON fixture. No production spreadsheet is stored in source control.</summary>
|
|
public static class KbxSyntheticImportWorkbook
|
|
{
|
|
private sealed record Fixture(string Sheet, string[] Columns, JsonElement[][] Rows);
|
|
|
|
public static void Build(string jsonPath, string xlsxPath)
|
|
{
|
|
var fixture = JsonSerializer.Deserialize<Fixture>(File.ReadAllText(jsonPath),
|
|
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
|
|
?? throw new InvalidOperationException("Invalid synthetic import fixture.");
|
|
|
|
using var workbook = new XLWorkbook();
|
|
var sheet = workbook.Worksheets.Add(fixture.Sheet);
|
|
for (var c = 0; c < fixture.Columns.Length; c++)
|
|
sheet.Cell(1, c + 1).Value = fixture.Columns[c];
|
|
|
|
for (var r = 0; r < fixture.Rows.Length; r++)
|
|
for (var c = 0; c < fixture.Rows[r].Length; c++)
|
|
{
|
|
var cell = sheet.Cell(r + 2, c + 1);
|
|
var value = fixture.Rows[r][c];
|
|
cell.Value = value.ValueKind switch
|
|
{
|
|
JsonValueKind.Number when value.TryGetDecimal(out var number) => number,
|
|
JsonValueKind.String => value.GetString() ?? string.Empty,
|
|
JsonValueKind.True => true,
|
|
JsonValueKind.False => false,
|
|
_ => value.ToString()
|
|
};
|
|
}
|
|
workbook.SaveAs(xlsxPath);
|
|
}
|
|
}
|