Click here to Skip to main content
14,391,917 members
Rate this:
Please Sign up or sign in to vote.
See more: , +
Please edit the code because I am unable to export the selected rows of DataGridView to Excel based on Checkbox selection .The below code export all the rows even those rows are not selected(checked) by the user.

What I have tried:

public void exportSelectedRowsToExcel()        {
            // creating Excel Application  
            Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
            // creating new WorkBook within Excel application  
            Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
            // creating new Excelsheet in workbook  
            Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
            // see the excel sheet behind the program  
            app.Visible = true;
            // get the reference of first sheet. By default its name is Sheet1.  
            // store its reference to worksheet  
            worksheet = workbook.Sheets["Sheet1"];
            worksheet = workbook.ActiveSheet;
            // changing the name of active sheet  
            worksheet.Name = DateTime.Now.ToString("yyyyMMddHHmmssfff");

                

            // storing header part in Excel  
            for (int i = 1; i < CategoryGV.Columns.Count + 1; i++)
            {
                worksheet.Cells[1, i] = CategoryGV.Columns[i - 1].HeaderText;
            }

            // storing Each row and column value to excel sheet  
            for (int i = 0; i < CategoryGV.Rows.Count - 1; i++)
            {
                for (int j = 0; j < CategoryGV.Columns.Count; j++)
                {
                    worksheet.Cells[i + 2, j + 1] = Convert.ToString(CategoryGV.Rows[i].Cells[j].Value);
                }
            }


            // save the application 
            workbook.SaveAs(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + 
                 "\\ExportedCategory.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
                  Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, 
                  Type.Missing, Type.Missing, Type.Missing);
            // Exit from the application  
            app.Quit();
        }


private void btnExportToExcel_Click(object sender, EventArgs e)
        {
            DataGridViewRow row = new DataGridViewRow();

            for (int i = 0; i < CategoryGV.Rows.Count; i++)
            {
                row = CategoryGV.Rows[i];
                if (Convert.ToBoolean(row.Cells["chkBox"].Value))
                {
                    int id = Convert.ToInt16(row.Cells["id"].Value);
                    exportSelectedRowsToExcel();
                    i--;
                }

            }
Posted
Updated 3-Dec-19 6:17am
v2
Comments
digimanus 3-Dec-19 9:12am
   
Wellllll where do you check if the row is selected? row.SelectedIndex is never used
Richard Deeming 3-Dec-19 9:15am
   
There is nothing in your code to check whether or not the rows are selected. You're just exporting every row.

You just need to add a test inside your loop:
Hide   Copy Code
for (int i = 0; i < CategoryGV.Rows.Count - 1; i++)


Edit: In fact, it's worse than that: you're exporting every row multiple times. If you have 10 rows in your grid, and 5 are selected, you export all 10 rows 5 times, overwriting the file each time.

Edit 2: Actually, it's even worse. Thanks to the i-- within the loop in your event handler, if any row is selected, your program will enter an infinite loop, exporting all rows over and over again until you terminate it.
Rate this:
Please Sign up or sign in to vote.

Solution 1

Add the test inside your loop in your exportSelectedRowsToExcel method:
for (int i = 0; i < CategoryGV.Rows.Count - 1; i++)
{
    var row = CategoryGV.Rows[i];
    if (Convert.ToBoolean(row.Cells["chkBox"].Value))
    {
        for (int j = 0; j < CategoryGV.Columns.Count; j++)
        {
            worksheet.Cells[i + 2, j + 1] = Convert.ToString(row.Cells[j].Value);
        }
    }
}
Then change your event handler so that it only exports the rows once:
private void btnExportToExcel_Click(object sender, EventArgs e)
{
    bool haveSelectedRows = false;
    
    for (int i = 0; i < CategoryGV.Rows.Count; i++)
    {
        var row = CategoryGV.Rows[i];
        if (Convert.ToBoolean(row.Cells["chkBox"].Value))
        {
            haveSelectedRows = true;
            break;
        }
    }
    
    if (haveSelectedRows)
    {
        exportSelectedRowsToExcel();
    }
}
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

first get all rows which are selected and pass those rows into your export method.
your export methods exports all cells all the time. ittirate only selected row.

var rows = new List<DataGridViewRow>();
for (int i = 0; i < CategoryGV.Rows.Count; i++)
    {
        var row = CategoryGV.Rows[i];
        if (Convert.ToBoolean(row.Cells["chkBox"].Value))
        {
            rows.add(row);
        }
    }

exportSelectedRowsToExcel(rows);

// storing Each row and column value to excel sheet  
foreach (var row in rows)
{
   for (int j = 0; j < CategoryGV.Columns.Count; j++)
    {
       worksheet.Cells[row.Index, j + 1] = Convert.ToString(row.Cells[j].Value);
     }
}
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100