Member Avatar for hueikar

Hi,
I would like to export data from datagridview into excel?
Can show me some example to do it?
Appreaciate it!

I do a lot of stuff with the MSFlexGrid...

I usually get real lazy when it comes to importing data into Excel.

What I normally do is export the grid and Tab Delimit the fields into a text file.

Then "Open With" Excel, after which I can save as a regular Excel File.


As to how to do it directly...

I've been too lazy to attack that problem, yet. :)

But, I suspect that after you build the export to Tab Delimited portion, and get it working, you can then learn how to access Excel and instead of writing to the text file write to the Excel Cells in your target workbook.

OK, took a look at the Datagrid and it does not allow access in a similar manner as the FlexGrid.

If I were you I would only use the datagrid to "see" your data and as an aid to selecting the data in the underlying database.

I would then look at selecting the appropriate Tables and fields and exporting them.

Again, I'd look at it as a two part excersize...

Export to a delimited Text File, first, and get that portion correct, selecting and exporting.

Then work on getting it into Excel.

Sorry, if my previous post caused any confusion.

I use the FlexGrid even for Databases and manually select Tables and Fields because it is much easier to loop through a FlexGrid using .textMatrix(row,col).

At least for me... :)

Member Avatar for hueikar

Thnx so much for you reply. Then i try to export into a text file. =)

Member Avatar for hueikar

Yes. I managed to save it into txt file.
Coding is as below and can rearrange it using excel.
Thank you.

Dim numCols As Integer = dgvExp.ColumnCount
        Dim numRows As Integer = dgvExp.RowCount - 1
        Dim strDestinationFile As String = "c:username.txt"
        Dim tw As TextWriter = New StreamWriter(strDestinationFile)

        'writing the header
        For count As Integer = 0 To numCols - 1
            tw.Write(dgvExp.Columns(count).HeaderText)
            If (count <> numCols - 1) Then
                tw.Write(", ")
            End If
        Next
        tw.WriteLine()
        For count As Integer = 0 To numRows - 1
            For count2 As Integer = 0 To numCols - 1
                tw.Write(dgvExp.Rows(count).Cells(count2).Value)
                If (count2 <> numCols) Then
                    tw.Write(", ")
                End If
            Next
            tw.WriteLine()
        Next
        tw.Close()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.