public static void ExportToExcel (DataGrid datagrid, Stream stream)
{
Workbook workbook = new Workbook();
Worksheet worksheet = new Worksheet("Sheet 1");
datagrid.UpdateLayout();
// IList source = datagrid.ItemsSource as IList ;
List<Test> source = new List<Test>();
for (int i = 0; i < datagrid.Columns.Count -1 ; i++)
{
source.Add(new Test() { Name = i.ToString() });
}
if (source == null)
return;
//Write column headers
for (int i = 0; i < datagrid.Columns.Count - 1; i++)
worksheet.Cells[0, i] = new Cell(datagrid.Columns[i].Header);
int rowIndex = 1; //Move up one row
int colIndex = 0;
foreach (Object data in datagrid.ItemsSource)
{
datagrid.ScrollIntoView(data, null);
for (int i = 0; i < datagrid.Columns.Count; i++)
{
string content = string.Empty;
FrameworkElement element = datagrid.Columns[i].GetCellContent(data);
if (element != null)
{
if (element is TextBlock)
{
content = (element as TextBlock).Text;
}
else if (element is HyperlinkButton)
{
content = (element as HyperlinkButton).Content.ToString();
}
}
//Write cell content
worksheet.Cells[rowIndex, colIndex] = new Cell(content);
colIndex++;
}
rowIndex++;
colIndex = 0;
}
datagrid.ScrollIntoView(source[0], null);
workbook.Worksheets.Add(worksheet);
workbook.Save(stream);
}