c# Export datagridview to excel without hidden columns

Viewed 23

i`m trying to export the datagridview to excel file but i made some columns in datagridview is visible how i can export only visible columns to excel file

my code

for (int i = 1; i < datagrid.Columns.Count + 1; i++)
{
    if(datagrid.Columns[i - 1].Visible)
        worksheet.Cells[1, i] = datagrid.Columns[i - 1].HeaderText;
}
for (int i = 0; i < datagrid.Rows.Count - 1; i++)
{
    for (int j = 0; j < datagrid.Columns.Count; j++)
    {
        if (datagrid.Columns[j].Visible)
            worksheet.Cells[i + 2, j + 1] = datagrid.Rows[i].Cells[j].Value.ToString(); //
    }
}

i get this result

enter image description here

there more columns in sheet is empty i wanna make it like this

enter image description here

0 Answers
Related