Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
4341
Problem in exporting column headers of XamDataGrid to excel using DataPresenterExcelExporter
posted

I have tried exporting XamDataGrid data records to excel it is working fine for XamDataGrid with data records but for empty XamDatagrid it is showing blank workbook.We want column headers to be exported in case if there is no data records in XamDataGrid.Is there any way by which we can export column headers when there is no data record in XamDataGrid?

  • 2677
    posted

    Hello,

    If your grid has no records in it, you can do an easy workaround.  You can check for no records in the button click event and if there are no records, you can add values to the first/header row so the header labels will be there.
     If you want to just export directly to a file, you can use the BeginExport event to modify the cells of the first/header row because you wont have any worksheet to work with if you do not create the workbook in the click event.

    Notice how the BeginExport event gives me an argument (e) with all the information that I need.

    Here is a code snippet of the buttonclick and the beginExport event handler.

    private void btnExport_Click(object sender, RoutedEventArgs e)
            {
                DataPresenterExcelExporter exporter = new DataPresenterExcelExporter();
                Workbook wb = new Workbook(WorkbookFormat.Excel2007);
                wb.Worksheets.Add("TestWorkSheet");
                if (this.XamGrid.Records.Count == 0)
                {
                    for (int i = 0; i < this.XamGrid.FieldLayouts[0].Fields.Count; i++)
                    {
                        wb.Worksheets["TestWorkSheet"].Rows[0].Cells[i].Value = this.XamGrid.FieldLayouts[0].Fields[i].Label;
                    }
                    //handle if you dont want to create the workbook in code and comment out above if statement
                    //exporter.BeginExport += new EventHandler<BeginExportEventArgs>(exporter_BeginExport);
                }
                exporter.Export(this.XamGrid, wb);
                wb.Save(@"C:\Users\sosterberg\Desktop\TestGridExport.xlsx");

                //If you choose to not create the workbook, use code similar to this and comment out above two lines.
                //exporter.Export(this.XamGrid, @"C:\Users\sosterberg\Desktop\TestGridExport.xlsx",                 WorkbookFormat.Excel2007);
            }

            void exporter_BeginExport(object sender, BeginExportEventArgs e)
            {
                for (int i = 0; i < e.DataPresenter.FieldLayouts[0].Fields.Count; i++)
                {
                    e.CurrentWorksheet.Rows[0].Cells[i].Value = e.DataPresenter.FieldLayouts[0].Fields[i].Label;
                }
            }