Search code examples
c#excelvisual-studio-2022windows-storewinui-3

How can I export data to an Excel file with APP WinUI3?


I don't know how to export data from a ListView to Excel using a Winui3 APP tecnology. With WPF I used "Excel = Microsoft.Office.Interop.Excel" but in WinUI3 technology it doesn't work

Excel._Workbook MyExBook;
Excel.Workbooks MyExBooks;
Excel._Worksheet MyExSheet;
Excel.Sheets MyExSheets;
Excel.Range MyExRange;
ButExcel.IsEnabled = false;

try
{
    MyExApp = new Excel.Application();
    MyExBooks = MyExApp.Workbooks;
    MyExBook = MyExBooks.Add();
    MyExSheets = MyExBook.Worksheets;
    MyExSheet = (Excel.Worksheet)MyExSheets[1];
}
catch
{
    ButExcel.IsEnabled = true;
    return;
}

Solution

  • There's no reason to use Excel itself to generate xlsx files. These files are ZIP packages containing well-defined XML files. There several libraries that can easily generate real Excel files, eg Epplus, ClosedXML, NPOI and many more.

    These libraries offer several convenience methods that can load data from collections, DataTables or DataReaders directly. For example, using EPPlus, you can create an Excel file from a list of Products with :

    var producs=new List<Product>();
    //Load the list somehow
    
    using (var p = new ExcelPackage())
    {
        var sheet = pck.Workbook.Worksheets.Add("sheet");
        var range = sheet.Cells["C1"].LoadFromCollection(products);
       
        p.SaveAs(new FileInfo(@"c:\workbooks\myworkbook.xlsx"));
    }
    

    You can load the data with headers, as a table, using one of the predefined styles too:

    var tableRange = sheet.Cells["C1"].LoadFromCollection(products, true, TableStyles.Dark1);
    // to get access to the created table:
    var table = sheet.Tables.GetFromRange(tableRange);
    

    ClosedXML allows writing similar code :

        var wb = new XLWorkbook();
        var ws = wb.Worksheets.Add("Inserting Data");
        var rangeWithPeople = ws.Cell(7, 6).InsertData(people.AsEnumerable());
    
        ...
        wb.SaveAs("InsertingData.xlsx");
    

    To create a table you need to use InsertTable instead of InsertData:

        var table= ws.Cell(7, 6).InsertTable(people.AsEnumerable(),"MyTable");
    

    Both libraries also work with DataTable results