export

To export the DataGrid content to an Excel (.xlsx) file, we’ll use ClosedXML — a popular .NET library for working with Excel files.


✅ Step-by-Step Update

📦 1. Install ClosedXML NuGet Package

Run this in Package Manager Console:

Install-Package ClosedXML

🧠 2. Update ViewModel (MainViewModel.cs)

Add a new command:

public ICommand ExportToExcelCommand => new RelayCommand(ExportToExcel);

Add this method to MainViewModel:

private void ExportToExcel()
{
    var dialog = new SaveFileDialog { Filter = "Excel Workbook (*.xlsx)|*.xlsx" };
    if (dialog.ShowDialog() == true)
    {
        using var workbook = new ClosedXML.Excel.XLWorkbook();
        var worksheet = workbook.Worksheets.Add("Command Results");

        worksheet.Cell(1, 1).Value = "Command ID";
        worksheet.Cell(1, 2).Value = "ADB Command";
        worksheet.Cell(1, 3).Value = "CAN Signal";
        worksheet.Cell(1, 4).Value = "Expected Value";
        worksheet.Cell(1, 5).Value = "Execution Time";
        worksheet.Cell(1, 6).Value = "Result";

        for (int i = 0; i < Commands.Count; i++)
        {
            var cmd = Commands[i];
            worksheet.Cell(i + 2, 1).Value = cmd.CommandId;
            worksheet.Cell(i + 2, 2).Value = cmd.AdbCommand;
            worksheet.Cell(i + 2, 3).Value = cmd.CanSignal;
            worksheet.Cell(i + 2, 4).Value = cmd.ExpectedValue;
            worksheet.Cell(i + 2, 5).Value = cmd.ExecutionTime.ToString("yyyy-MM-dd HH:mm:ss");
            worksheet.Cell(i + 2, 6).Value = cmd.Result;
        }

        workbook.SaveAs(dialog.FileName);
    }
}

🖼 3. Update View (MainWindow.xaml)

Add this after the other buttons:

<Button Content="Export to Excel" Command="{Binding ExportToExcelCommand}" Margin="5"/>

This exports the DataGrid's contents to an Excel file with formatting.
Would you like to also style the Excel output (e.g. color Fail rows red)?

Comments

Popular posts from this blog

My work

color change