Excel Ausgabe in C# mit WPF Datagrid

 

Das Nuget Paket Microsoft.Office.Interop.Excel installieren. Die Daten werden aus dem Datagrid und dem zugrundelegenden Binding Objekt – in diesem Fall List aufgebaut.

 

using Excel = Microsoft.Office.Interop.Excel;

 

public static void Exel1(List<Person> personen, DataGrid dataGrid)
{

var excelApp = new Excel.Application();
// Make the object visible.
excelApp.Visible = true;

// Create a new, empty workbook and add it to the collection returned
// by property Workbooks. The new workbook becomes the active workbook.
// Add has an optional parameter for specifying a praticular template.
// Because no argument is sent in this example, Add creates a new workbook.
excelApp.Workbooks.Add();

// This example uses a single workSheet. The explicit type casting is
// removed in a later procedure.
Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
Microsoft.Office.Interop.Excel.Range headerColumnRange = workSheet.get_Range(„A1“, „G1“);
headerColumnRange.Font.Bold = true;
// headerColumnRange.Font.Color = 0xFF0000;

int col = 0;
List<String> celllist = new List<string>();
for (col = 0; col < dataGrid.Columns.Count; col++)
{
workSheet.Cells[1, col + 1] = dataGrid.Columns[col].Header.ToString();

}

var row = 1;
foreach (var p in personen)
{
row++;
for (col = 0; col < dataGrid.Columns.Count; col++)
{
var item = p.GetType().GetProperty(dataGrid.Columns[col].SortMemberPath.ToString()).GetValue(p, null); ;
workSheet.Cells[row, col + 1] = item;

}

}

for (col = 0; col < dataGrid.Columns.Count; col++)
{
workSheet.Columns[col + 1].AutoFit();

}

}
}