Jump to content

Recommended Posts

Posted

Olá P@P, Estou a trabalhar numa aplicação que exporta os dados de uma listview para o Excel 2003,

o problema é: ao exportar dados do campo Código (Ex.: 0001230) para o Excel são ignorados os zeros iniciais (Ex.: 1230)

Há uma solução pra isso? preciso de uma ajuda.

E mais, também não consigo exportar uma imagem para o Excel.

@ pr@tic@ f@z o m&str&

Posted

Boa tarde...

Vê se é isti que precisas...

Protected Sub ExportaExcel(ByVal sender As Object, ByVal e As System.EventArgs) Handles ExportaExcel1.Click
        If Not Flag Then
            'Verificar se a datagridview tem dados
            If ((GridView1.Columns.Count = 0) Or (GridView1.Rows.Count = 0)) Then
                Exit Sub
            End If

            'Cria um dataset com os dados do Gridview para exportar
            Dim dset As New DataSet
            'cria a tabela do dataset
            dset.Tables.Add()

            'Adiciona as colunas do GridView na tabela
            For i As Integer = 0 To GridView1.Columns.Count - 1
                dset.Tables(0).Columns.Add(GridView1.Columns(i).HeaderText)
            Next

            'Adiciona linhas com os dados na tabela
            Dim dr1 As DataRow
            For i As Integer = 0 To GridView1.Rows.Count - 1
                dr1 = dset.Tables(0).NewRow
                For j As Integer = 0 To GridView1.Columns.Count - 1
                    dr1(j) = GridView1.Rows(i).Cells(j).Text
                Next
                dset.Tables(0).Rows.Add(dr1)
            Next

            Dim excel As New Microsoft.Office.Interop.Excel.ApplicationClass
            Dim wBook As Microsoft.Office.Interop.Excel.Workbook
            Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet

            wBook = excel.Workbooks.Add()
            wSheet = wBook.ActiveSheet()

            'Cria Cabeçalho da folha de Cálculo
            Dim logo As String = Server.MapPath("~\Imagens\Logotipo.jpg")
            wSheet.Shapes.AddPicture(logo, 0, 1, 45, 10, 200, 62)
            excel.Rows(2).RowHeight = 30
            'excel.Range("E2:K2").MergeCells = True
            excel.Range("E2").Value = "TURMA"
            'excel.Range("E3:K3").MergeCells = True
            excel.Range("E3").Value = Session("Turma")

            excel.Range("E2:E3").Font.Bold = True
            excel.Range("E2:E3").Font.Size = 14
            excel.Range("E2:E3").Font.Name = "Verdana"
            excel.Range("E2:E3").HorizontalAlignment = XlHAlign.xlHAlignCenter
            excel.Range("E2:E3").VerticalAlignment = XlVAlign.xlVAlignCenter

            excel.Rows(3).RowHeight = 30
            excel.Rows(5).RowHeight = 2
            excel.Cells.Range("B5:E5").Interior.Color = RGB(0, 0, 0)

            Dim dt As System.Data.DataTable = dset.Tables(0)
            Dim dc As System.Data.DataColumn
            Dim dr As System.Data.DataRow
            Dim colIndex As Integer = 1
            Dim rowIndex As Integer = 5
            Dim topo As Integer = 70

            For Each dc In dt.Columns
                colIndex = colIndex + 1
                excel.Cells(6, colIndex) = dc.ColumnName

                'Formatação do texto da primeira linha
                excel.Cells(6, colIndex).HorizontalAlignment = XlHAlign.xlHAlignCenter
                excel.Cells(6, colIndex).Font.Bold = True

                'Modifica Largura da Coluna
                Select Case colIndex
                    Case 2
                        excel.Columns(colIndex).ColumnWidth = 8
                    Case 3
                        excel.Columns(colIndex).ColumnWidth = 11.9
                    Case 4
                        excel.Columns(colIndex).ColumnWidth = 8
                    Case 5
                        excel.Columns(colIndex).ColumnWidth = 60
                End Select
            Next

            For Each dr In dt.Rows
                rowIndex = rowIndex + 1
                topo = topo + 42
                colIndex = 1
                'Modifica ALtura da Linha
                excel.Rows(rowIndex + 1).RowHeight = 42
                For Each dc In dt.Columns
                    colIndex = colIndex + 1
                    excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)

                    'Alinhamento dentro das células
                    excel.Cells(rowIndex + 1, colIndex).VerticalAlignment = XlVAlign.xlVAlignCenter
                    If colIndex = 3 Or colIndex = 4 Or colIndex > 5 Then
                        excel.Cells(rowIndex + 1, colIndex).HorizontalAlignment = XlHAlign.xlHAlignCenter
                        If colIndex > 5 Then
                            excel.Cells(5, colIndex).Interior.Color = RGB(0, 0, 0)
                        End If
                    End If

                    'Inserir uma imagem na folha de cálculo
                    If colIndex = 3 Then
                        Dim a = dr(dc.ColumnName)
                        Dim fotoaluno As String = "Imagens\FotosAlunos\" & a & ".jpg"
                        If MyFunc.ExisteFicheiro(fotoaluno) Then
                            fotoaluno = Server.MapPath("~\" & fotoaluno)
                            wSheet.Shapes.AddPicture(fotoaluno, 0, 1, 55, topo, 30, 36)
                        Else
                            fotoaluno = Server.MapPath("~\Imagens\FotosAlunos\0000.jpg")
                            wSheet.Shapes.AddPicture(fotoaluno, 0, 1, 55, topo, 30, 36)
                        End If
                    End If
                Next
                excel.Cells.Range(excel.Cells(2, 5), excel.Cells(2, colIndex)).MergeCells = True
                excel.Cells.Range(excel.Cells(3, 5), excel.Cells(3, colIndex)).MergeCells = True
            Next

            'wSheet.Columns.AutoFit()

            Dim strFileName As String = "~\FolhasExcel\Aval" & Session("Turma") & ".xls"
            strFileName = Server.MapPath(strFileName)
            Dim blnFileOpen As Boolean = False

            If System.IO.File.Exists(strFileName) Then
                System.IO.File.Delete(strFileName)
            End If

            Try
                Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(strFileName)
                fileTemp.Close()
            Catch ex As Exception
                blnFileOpen = False
            End Try

            Try
                wBook.SaveAs(strFileName)
                excel.Workbooks.Open(strFileName)
            Catch ex As Exception

            End Try

            excel.Visible = True
            Flag = True
        Else
            Flag = False
        End If
    End Sub

tens que o adaptar...

Cordiais cumprimentos,

Security

"Innovation distinguishes between a leader and a follower." Steve jobs.

Posted

O código é optimo Exporta uma imagem p/ Excel mas o meu maior problema é exportar dados numéricos que iniciam com o valor (zero) sem serem ignorados pelo Excel

Ex.:  0001230 (No DataGridView) -->> 1230 (No Excell)

E mais, Xtou usando Windows Forms e ñ um Web Forms. 😞

@ pr@tic@ f@z o m&str&

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.