Link to home
Start Free TrialLog in
Avatar of printmedia
printmedia

asked on

Datagridview column when exported to Excel changes vb.net

Hi all.

I have a datagridview control with various columns, the first column in the datagridview control is the CustomerDivision.

The values are: 00, 01, 02 and 03

They appear correctly in the datagridview control but when I export them to Excel they appear as 0, 1, 2 and 3. Excel cuts off the leading zero.

When I created the datatable that populates the datagridview control I told it it was of type String:

newDT.Columns.Add("CustomerDivision", System.Type.GetType("System.String"))

Open in new window


Here is the code that exports the datagridview data to Excel:
Dim oXLApp As Excel.Application       'Declare the object variables
        Dim oXLBook As Excel.Workbook
        Dim oXLSheet As Excel.Worksheet

        oXLApp = New Excel.Application  'Create a new instance of Excel
        oXLBook = oXLApp.Workbooks.Add  'Add a new workbook
        oXLSheet = oXLBook.Worksheets(1)  'Work with the first worksheet

        oXLApp.Visible = True               'Show it to the user

        With oXLApp
            Dim Col As DataGridViewColumn
            Dim i As Integer = 1
            For Each Col In DataGridView1.Columns
                .Cells(1, i).Value = Col.HeaderText
                i += 1
            Next
            i = 2
            Dim RowItem As DataGridViewRow
            Dim Cell As DataGridViewCell
            For Each RowItem In DataGridView1.Rows
                Dim j As Integer = 1
                For Each Cell In RowItem.Cells
                    .Cells(i, j).Value = Cell.Value
                    j += 1
                Next
                i += 1
            Next

        End With
oXLSheet.UsedRange.Borders.LineStyle = 1
        oXLApp.Columns.AutoFit()

        oXLSheet.Range("A1:I1").Font.Bold = True
        oXLSheet.Range("I" & ":" & "I").NumberFormat = "#.0%"

oXLBook = Nothing       'Disconnect from Excel (let the user take over)
        oXLApp = Nothing
        oXLSheet = Nothing

Open in new window


Any idea how I can tell Excel that's ok to keep the leading zero, only to the first column?

Thank you in advance.
ASKER CERTIFIED SOLUTION
Avatar of Wayne Taylor (webtubbs)
Wayne Taylor (webtubbs)
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial