Exporting Several XtraGrid Controls to a Single Excel File

richardtk_1 picture richardtk_1 · Apr 25, 2012 · Viewed 12.1k times · Source

I've got several XtraGrid Controls each one containing different information, I get some information about the way in which you can export a XtraGrid to an Excel file in the following direction http://www.devexpress.com/Support/Center/p/Q362120.aspx

Now Is there any way to export the each XtraGrid Control to a single Excel file so that every XtraGrid information is exported to a different excel sheet.

I tried setting the exporting path direction to the same Excel file, but when the first exporting process is done, the second exporting process just overrides the excel file and so on.

I tried using the method described in this direction XtraGrid - Export To Excel , but I wanted to know if there is another way whithout using the interop excel libraries because I have experience some problems when using this library (I mean when using this library you create an Excel process but after you created it you cannot kill it, even though you have used the method that is supposed to do that).

Any help would be welcomed.

Answer

speckledcarp picture speckledcarp · Jun 20, 2013

I just wanted to provide a more complete answer, since it took a while for me to get a solution together using D..'s answer.

And yes - it looks like I'm trying to print something, but I'm just exporting to Excel, I promise.

using DevExpress.XtraPrinting;
using DevExpress.XtraPrintingLinks;
using DevExpress.XtraGrid;

class whatever
{
    GridControl grid1;
    GridControl grid2;
    //.....

    public void exportToExcel()
    {
        using (var saveDialog = new SaveFileDialog())
        {
            saveDialog.Filter = "Excel (.xlsx)|*.xlsx";
            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                var printingSystem = new PrintingSystemBase();
                var compositeLink = new CompositeLinkBase();
                compositeLink.PrintingSystemBase = printingSystem;

                var link1 = new PrintableComponentLinkBase();
                link1.Component = grid1;
                var link2 = new PrintableComponentLinkBase();
                link2.Component = grid2;

                compositeLink.Links.Add(link1);
                compositeLink.Links.Add(link2);

                var options = new XlsxExportOptions();
                options.ExportMode = XlsxExportMode.SingleFilePageByPage;

                compositeLink.CreatePageForEachLink();
                compositeLink.ExportToXlsx(saveDialog.FileName, options);
            }
        }
    }
}    

Hope it saves somebody a little time.