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() {
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = DateTime.Now.ToString("yyyyMMddHHmmssfff");
for (int i = 1; i < CategoryGV.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = CategoryGV.Columns[i - 1].HeaderText;
}
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);
}
}
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);
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--;
}
}