none
How to export data from multiple datagridview into excel sheets of a single excel file in C# RRS feed

  • Question

  • I have tried answers posted on the forum but those answers does not work.

    Please help me out for this problem.

    Regards,

    Krishna

    Tuesday, December 22, 2015 5:29 AM

Answers

  • >>>I have tried answers posted on the forum but those answers does not work.

    Please help me out for this problem.<<<

    If you want to export data from datagridview into excel sheets of a single excel file in C#, you could add reference Microsoft.Office.Interop.Excel dll then refer to below code:

    using Excel = Microsoft.Office.Interop.Excel; 
    
    Excel.Application xlApp ;
    Excel.Workbook xlWorkBook ;
    Excel.Worksheet xlWorkSheet ;
    object misValue = System.Reflection.Missing.Value;
    
    xlApp = new Excel.Application();
    xlWorkBook = xlApp.Workbooks.Add(misValue);
    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
    int i = 0;
    int j = 0; 
    for (i = 0; i <= dataGridView1.RowCount  - 1; i++)
    {
        for (j = 0; j <= dataGridView1.ColumnCount  - 1; j++)
        {
             DataGridViewCell cell = dataGridView1[j, i];
             xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
        }
    }
    
    xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
    xlWorkBook.Close(true, misValue, misValue);
    xlApp.Quit();
    

    For more information, click here to refer about How to: Access Office Interop Objects by Using Visual C# Features (C# Programming Guide)

    Otherwise could you provide more information about your issue, for example sample code, screenshot, exception etc., that will help us reproduce and resolve your issue.

    Thanks for your understanding.

    Wednesday, December 23, 2015 2:20 AM