question

ravikumar-1532 avatar image
0 Votes"
ravikumar-1532 asked ravikumar-1532 commented

excel export datagrid view with headers

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


dotnet-csharpvs-generalwindows-forms
image.png (12.4 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Viorel-1 avatar image
0 Votes"
Viorel-1 answered ravikumar-1532 commented

Maybe try replacing

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

with

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



· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@Viorel-1 thank you so much ...you are a life saver

0 Votes 0 ·