Click here to Skip to main content
15,887,821 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi all i have created a export to excel button that exports my datagrid, but the question now is i want to know how to add a header on top of my excel when its created

below is my code

What I have tried:

VB
    'create empty string
    Dim thecsvfile As String = String.Empty
    'get the column headers
    For Each column As DataGridViewColumn In Datagrid.Columns
        thecsvfile = thecsvfile & column.HeaderText & ","
    Next
    'trim the last comma
    thecsvfile = thecsvfile.TrimEnd(",")
    'Add the line to the output
    thecsvfile = thecsvfile & vbCr & vbLf
    'get the rows
    For Each row As DataGridViewRow In Datagrid.Rows
        'get the cells
        For Each cell As DataGridViewCell In row.Cells
            thecsvfile = thecsvfile & cell.FormattedValue.replace(",", "") & ","
        Next
        'trim the last comma
        thecsvfile = thecsvfile.TrimEnd(",")
        'Add the line to the output
        thecsvfile = thecsvfile & vbCr & vbLf
    Next
    'write the file
    My.Computer.FileSystem.WriteAllText("C:\Inventory System\Inventory Datasheet.csv", thecsvfile, False)
End Sub
Posted
Updated 10-Jan-18 8:27am
v2
Comments
Jochen Arndt 8-Jan-18 5:21am    
You are creating a CSV file with a header line. When importing that with Excel, you can specify that the file contains a header line and Excel will use the first line as header.

However, you have to ensure that your grid view has the column headers set.
Tyson Junior Ratbag Ling 8-Jan-18 5:29am    
okay thanks for your respond. im new in coding and hope you could help me fix that cause i do not know
Karthik_Mahalingam 8-Jan-18 5:31am    
use  Reply  button, to post Comments/query to the user, so that the user gets notified and responds to your text.
Richard MacCutchan 8-Jan-18 5:48am    
Do the headers exist in the generated csv file?

1 solution

To be honest, your code doesn't export data of datagridview into Excel. It's exporting data into text file in csv format[^].

If you want to export data into Excel file (*.xls or *.xlsx), check past answers: Export datagridview to excel With Column headers[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900