I need to export data from DataGridView into Excel, but only selected cells. DataGridView is bounded to DataTable. I've seen a lot of examples of how to copy selected rows, but can't find on how to copy only selected cells into new DataTable. This is what I've tried so far:
//First, copy structure of DataTable into new one
DataTable dt = ((DataTable)dgv.DataSource).Clone();
//Then insert data into new datatable
foreach (DataGridViewCell cell in dgv.SelectedCells)
{
//We get Index of column and row from bounded DataTable
int col_indx = ((DataTable)dgv.DataSource).Columns.IndexOf(dgv.Columns[cell.ColumnIndex].Name);
int row_indx = ((DataTable)dgv.DataSource).Rows.IndexOf(((DataRowView)dgv.Rows[cell.RowIndex].DataBoundItem).Row);
//First check if row already exists
if (dt.Columns.Contains(dgv.Columns[cell.ColumnIndex].Name))
{
DataRow newrow = dt.NewRow();
newrow[col_indx] = cell.Value;
dt.Rows.InsertAt(newrow, row_indx);
}
else
{
dt.Rows[row_indx][cell_indx] = cell.Value;
}
}
dt.AcceptChanges();
This part inserts data into new DataTable, but on separate rows If I select some cells from same row. How can I fix this ?
EDIT:
for (int i = 0; i < dgv.Rows.Count; i++)
{
dt.Rows.Add();
for (int j = 0; j < dgv.ColumnCount; j++)
{
if (dgv.Rows[i].Cells[j].Selected == true)
{
dt.Rows[i][j] = dgv.Rows[i].Cells[j].Value;
}
}
}
dt.AcceptChanges();
This is closest thing I could achieve. It copies selected data into new DataTable, but unfortunally It preserves empty rows too. So when I select cells in Datagridview from e.g. 3th row, the output in Excel is going to be with first 2 rows empty. I want to avoid that, but how ?...In other words, what I select in Datagridview must start in new Datatable from row 1 and so on...