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)
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--;
}
}
}
========================================================================== 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();
}