Na verão anterior do programa, o grid era carregado a partir de um datatable e posteriormente poderíamos exortar os dados para o excel usando o seguinte código:
private void paraExcel(string titulo)
{
Task.Factory.StartNew(() =>
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
_busyIndicator.IsBusy = true;
tblBusyTitulo.Text = "Exportando para o Excel";
tbllBusyContent.Text = "Aguarde...";
}));
Microsoft.Office.Interop.Excel.Application excel = null;
Microsoft.Office.Interop.Excel.Workbook wb = null;
object missing = Type.Missing;
Microsoft.Office.Interop.Excel.Worksheet ws = null;
try
{
excel = new Microsoft.Office.Interop.Excel.Application();
wb = excel.Workbooks.Add();
ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.ActiveSheet;
for (int Idx = 0; Idx < dtGeral.Columns.Count; Idx++)
{
ws.Range["A1"].Offset[0, Idx].Value = dtGeral.Columns[Idx].ColumnName;
}
for (int Idx = 0; Idx < dtGeral.Rows.Count; Idx++)
{
ws.Range["A2"].Offset[Idx].Resize[1, dtGeral.Columns.Count].Value =
dtGeral.Rows[Idx].ItemArray;
}
excel.Visible = true;
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
_busyIndicator.IsBusy = false;
}));
}
catch (COMException ex)
{
MessageBox.Show("Erro ao Acessar o Excel: " + ex.ToString());
}
catch (Exception ex)
{
MessageBox.Show("Erro Geral: " + ex.ToString());
}
});
}
Na versão atual, o datagrid é preenchido a partir de um ObservableCollection e, portnto, o código acima é inútil... alguem poderia me dar uma dica de como fazer pra exportar do datagrid para o excel nesta nova versão?
Se a resposta foi útil, por favor marque como útil. Leia a bíblia.