excel export datagrid view with headers

ravi kumar 331 Reputation points
2020-12-17T09:13:23.417+00:00

Hello all ,

i have this below code to export my datagrid view o a CSV format , which i can open in excel later , but the datagrid headers are not getting exported , kindly help me how to include headers of my data grid view while exporting:

private void btnexcelexport_Click(object sender, EventArgs e)  
        {  
            int cols;  
            //open file   
            StreamWriter wr = new StreamWriter(@"C:\Users\ramadasr\Documents\Export.csv", false, Encoding.UTF8);  
  
            //determine the number of columns and write columns to file   
            cols = iP_SpoolsDataGridView.Columns.Count;  
            for (int i = 0; i < cols; i++)  
            {  
                wr.Write(iP_SpoolsDataGridView.Columns[i].Name.ToString().ToUpper() + ",");  
            }  
            wr.WriteLine();  
  
            //write rows to excel file  
            for (int i = 0; i < (iP_SpoolsDataGridView.Rows.Count); i++)  
            {  
                for (int j = 0; j < cols; j++)  
                {  
                    if (iP_SpoolsDataGridView.Rows[i].Cells[j].Value != null)  
                    {  
                        wr.Write(iP_SpoolsDataGridView.Rows[i].Cells[j].Value + ",");  
                    }  
                    else  
                    {  
                        wr.Write(",");  
                    }  
                }  
  
                wr.WriteLine();  
            }  
            //close file  
            wr.Close();  
        }  

here is the image of my exported view:
48967-image.png

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,903 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,189 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,006 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 118K Reputation points
    2020-12-17T09:23:02.85+00:00

    Maybe try replacing

    wr.Write(iP_SpoolsDataGridView.Columns[i].Name.ToString().ToUpper() + ",");
    

    with

    wr.Write(iP_SpoolsDataGridView.Columns[i].HeaderText.ToUpper() + ",");
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.