Jump to content
Alexandre Fonseca Dargelio

Formatar Data ao Exportar dados do DataGridView para Excel

Recommended Posts

Alexandre Fonseca Dargelio

Olá a Todos!

Sou absolutamente leigo em programação, mas a partir das minhas pesquisas e estudos, consegui exportar os dados de um DataGridView para o Excel com o código a seguir. Agora, preciso de saber como incluir a orientação para:

1) Formatar uma coluna - coluna C - para data ("dd/MM/yyyy") e outras duas para número - colunas F e L.;

2) Formatar a largura das colunas de acordo com o texto.

Agradeço desde já sua atenção e auxílio. 

 

Public Sub Exportar()
        Dim SAVE As New SaveFileDialog
        Dim way As String
        Dim xlApp As Object = CreateObject("Excel.Application")
        Dim pth As String = ""
        'criaremos una nova Plan
        Dim xlwb As Object = xlApp.WorkBooks.add
        Dim xlws As Object = xlwb.WorkSheets(1)
        Try


            For c As Integer = 0 To DataGridView1.Columns.Count - 1
                xlws.cells(1, c + 1).value = DataGridView1.Columns(c).HeaderText
            Next


            For r As Integer = 0 To DataGridView1.RowCount - 1
                For c As Integer = 0 To DataGridView1.Columns.Count - 1
                    xlws.cells(r + 2, c + 1) = DataGridView1.Item(c + 1, r + 2).Value.ToString()
                Next
            Next


            Dim SaveFileDialog1 As SaveFileDialog = New SaveFileDialog
            SaveFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
            SaveFileDialog1.Filter = "Archivo Excel| *.xlsx"
            SaveFileDialog1.FilterIndex = 2
            If SaveFileDialog1.ShowDialog = DialogResult.OK Then
                way = SaveFileDialog1.FileName
                xlwb.saveas(way)
                xlws = Nothing
                xlwb = Nothing
                xlApp.quit()
                MsgBox("Exportado Corretamente.")
            End If
        Catch ex As Exception
        End Try
    End Sub

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.