IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

ASP.NET Discussion :

Génération d'un fichier word


Sujet :

ASP.NET

  1. #1
    Membre éclairé Avatar de paradeofphp
    Inscrit en
    Décembre 2005
    Messages
    313
    Détails du profil
    Informations forums :
    Inscription : Décembre 2005
    Messages : 313
    Par défaut Génération d'un fichier word
    Bonjour

    Je suis entrain d'apprendre comment générer un fichier Word avec Vb.net.
    J'ai pris l'exemple se trouvant surle site de Microsoft :

    http://support.microsoft.com/kb/316383

    Dans mon cas, j'ai pas mis le à la fin de ma procédure.

    En executant tout se passe bien mais le fichier Word n'apparaît pas

    J'ai essayé egalement comme demandé d'ajouter cette ligne :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Imports Word = Microsoft.Office.Interop.Word
    Mais ca donne erreur.

    Quelqu'un a une idée de ce qui manque ? Merci

  2. #2
    Membre expérimenté
    Avatar de zooffy
    Homme Profil pro
    Chef de projet MOA
    Inscrit en
    Août 2004
    Messages
    3 895
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 55
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Chef de projet MOA
    Secteur : Bâtiment

    Informations forums :
    Inscription : Août 2004
    Messages : 3 895
    Par défaut
    Le Me.Close est importnat sinon tu vas charger la mémoire de ton serveur et il va se retourner.

    Sinon, donne plutôt le code de ta page où se passe l'appel du fichier Word. J'ai fait un truc dans ce genre là au printemps, mais c'était en ASP 3.0. Le problème que j'ai eu au départ c'est que je n'avasi pas compris qu'il fallait faire un lien (Hyperlien, ou bouton ou autre, peu importe) directement sur le fichier .DOC une fois généré.

    Kenavo

  3. #3
    Membre éclairé Avatar de paradeofphp
    Inscrit en
    Décembre 2005
    Messages
    313
    Détails du profil
    Informations forums :
    Inscription : Décembre 2005
    Messages : 313
    Par défaut
    Merci pour ta réponse zoofy

    Mais le Me.close va me fermer toute page chose que je veux pas faire. Sinon le code je l'ai mis dans un bouton exporter comme suit :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
            Private Sub btnExporter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnExporter.Click
     
                Try
     
                    Dim oWord As Word.Application
                    Dim oDoc As Word.Document
                    Dim oTable As Word.Table
                    Dim oPara1 As Word.Paragraph, oPara2 As Word.Paragraph
                    Dim oPara3 As Word.Paragraph, oPara4 As Word.Paragraph
                    Dim oRng As Word.Range
                    Dim oShape As Word.InlineShape
                    Dim oChart As Object
                    Dim Pos As Double
     
                    'Start Word and open the document template.
                    oWord = CreateObject("Word.Application")
                    oWord.Visible = True
                    oDoc = oWord.Documents.Add
     
                    'Insert a paragraph at the beginning of the document.
                    oPara1 = oDoc.Content.Paragraphs.Add
                    oPara1.Range.Text = "Heading 1"
                    oPara1.Range.Font.Bold = True
                    oPara1.Format.SpaceAfter = 24    '24 pt spacing after paragraph.
                    oPara1.Range.InsertParagraphAfter()
     
                    'Insert a paragraph at the end of the document.
                    '** \endofdoc is a predefined bookmark.
                    oPara2 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range)
                    oPara2.Range.Text = "Heading 2"
                    oPara2.Format.SpaceAfter = 6
                    oPara2.Range.InsertParagraphAfter()
     
                    'Insert another paragraph.
                    oPara3 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range)
                    oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:"
                    oPara3.Range.Font.Bold = False
                    oPara3.Format.SpaceAfter = 24
                    oPara3.Range.InsertParagraphAfter()
     
                    'Insert a 3 x 5 table, fill it with data, and make the first row
                    'bold and italic.
                    Dim r As Integer, c As Integer
                    oTable = oDoc.Tables.Add(oDoc.Bookmarks.Item("\endofdoc").Range, 3, 5)
                    oTable.Range.ParagraphFormat.SpaceAfter = 6
                    For r = 1 To 3
                        For c = 1 To 5
                            oTable.Cell(r, c).Range.Text = "r" & r & "c" & c
                        Next
                    Next
                    oTable.Rows.Item(1).Range.Font.Bold = True
                    oTable.Rows.Item(1).Range.Font.Italic = True
     
                    'Add some text after the table.
                    'oTable.Range.InsertParagraphAfter()
                    oPara4 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range)
                    oPara4.Range.InsertParagraphBefore()
                    oPara4.Range.Text = "And here's another table:"
                    oPara4.Format.SpaceAfter = 24
                    oPara4.Range.InsertParagraphAfter()
     
                    'Insert a 5 x 2 table, fill it with data, and change the column widths.
                    oTable = oDoc.Tables.Add(oDoc.Bookmarks.Item("\endofdoc").Range, 5, 2)
                    oTable.Range.ParagraphFormat.SpaceAfter = 6
                    For r = 1 To 5
                        For c = 1 To 2
                            oTable.Cell(r, c).Range.Text = "r" & r & "c" & c
                        Next
                    Next
                    oTable.Columns.Item(1).Width = oWord.InchesToPoints(2)   'Change width of columns 1 & 2
                    oTable.Columns.Item(2).Width = oWord.InchesToPoints(3)
     
                    'Keep inserting text. When you get to 7 inches from top of the
                    'document, insert a hard page break.
                    Pos = oWord.InchesToPoints(7)
                    oDoc.Bookmarks.Item("\endofdoc").Range.InsertParagraphAfter()
                    Do
                        oRng = oDoc.Bookmarks.Item("\endofdoc").Range
                        oRng.ParagraphFormat.SpaceAfter = 6
                        oRng.InsertAfter("A line of text")
                        oRng.InsertParagraphAfter()
                    Loop While Pos >= oRng.Information(Word.WdInformation.wdVerticalPositionRelativeToPage)
                    oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
                    oRng.InsertBreak(Word.WdBreakType.wdPageBreak)
                    oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
                    oRng.InsertAfter("We're now on page 2. Here's my chart:")
                    oRng.InsertParagraphAfter()
     
                    'Insert a chart and change the chart.
                    oShape = oDoc.Bookmarks.Item("\endofdoc").Range.InlineShapes.AddOLEObject( _
                        ClassType:="MSGraph.Chart.8", FileName _
                        :="", LinkToFile:=False, DisplayAsIcon:=False)
                    oChart = oShape.OLEFormat.Object
                    oChart.charttype = 4 'xlLine = 4
                    oChart.Application.Update()
                    oChart.Application.Quit()
                    'If desired, you can proceed from here using the Microsoft Graph 
                    'Object model on the oChart object to make additional changes to the
                    'chart.
                    oShape.Width = oWord.InchesToPoints(6.25)
                    oShape.Height = oWord.InchesToPoints(3.57)
     
                    'Add text after the chart.
                    oRng = oDoc.Bookmarks.Item("\endofdoc").Range
                    oRng.InsertParagraphAfter()
                    oRng.InsertAfter("THE END.")
     
                Catch ex As Exception
                    UniLog.Log(ex, Me)
                    lblMessage.Text = erreur(ex.Message)
                    lblMessage.Visible = True
     
                End Try
            End Sub

  4. #4
    Membre expérimenté
    Avatar de zooffy
    Homme Profil pro
    Chef de projet MOA
    Inscrit en
    Août 2004
    Messages
    3 895
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 55
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Chef de projet MOA
    Secteur : Bâtiment

    Informations forums :
    Inscription : Août 2004
    Messages : 3 895
    Par défaut
    Au fait, j'aurais du y penser plus tôt : as tu installer Word sur le serveur où se trouve IIS ?

    Parce que ça aussi, c'est sympa....

    Sinon, j'essaie de reprendre ton code mais je suis trés ennuyé : dans mes Imports, j'ai pas Microsoft.Office. et je trouve pas le moyen de la mettre. Je crois qu'il doit me manquer une DLL, mais je l'a trouve pas.

    C'est con, parce que en t'aidant à trouver, je bosse aussi pour moi. Mon truc ne ASP 3.0, va falloir que je le migre en .NET vers le mois d'Octobre.

    Kenavo

  5. #5
    Membre éclairé Avatar de paradeofphp
    Inscrit en
    Décembre 2005
    Messages
    313
    Détails du profil
    Informations forums :
    Inscription : Décembre 2005
    Messages : 313
    Par défaut
    ca marche la, j'ai dû rajouté ceci à la fin de ma procédure

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
                    oDoc.SaveAs("c:\TrombiDoc.doc")
                    oDoc.Close()
     
     
                    oWord = Nothing        '-- détruire l'objet Document
                    oDoc = Nothing        '-- détruire l'objet Word
    et j'ai bien le fichier qui est stocké dans c:. Merci à tous.

  6. #6
    Membre expérimenté
    Avatar de zooffy
    Homme Profil pro
    Chef de projet MOA
    Inscrit en
    Août 2004
    Messages
    3 895
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 55
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Chef de projet MOA
    Secteur : Bâtiment

    Informations forums :
    Inscription : Août 2004
    Messages : 3 895
    Par défaut
    ah ben oui, si tu sauve pas le document, ben....... pouet.

    Je viens juste de trouver la réfénrece qu'il me manquait pour faire un test, j'aurais certainement trouvé au premier clique.

    Ben en tout cas merci à toi d'avoir eu ce problème, ça m'a permis de ne pas l'avoir dans un mois ou deux.

  7. #7
    Membre expérimenté
    Avatar de zooffy
    Homme Profil pro
    Chef de projet MOA
    Inscrit en
    Août 2004
    Messages
    3 895
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 55
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Chef de projet MOA
    Secteur : Bâtiment

    Informations forums :
    Inscription : Août 2004
    Messages : 3 895
    Par défaut
    Euh, pourrais tu me filer ta procédure qui marche, parce que moi, ça plante.

    Mais je pense que j'ai du me gourrer sur un copier coller.

  8. #8
    Membre éclairé Avatar de paradeofphp
    Inscrit en
    Décembre 2005
    Messages
    313
    Détails du profil
    Informations forums :
    Inscription : Décembre 2005
    Messages : 313
    Par défaut
    salut,
    oui avec plaisir, mais la j'ai pris un congé et je suis pas au boulot. je rentrerai Mercredi prochain et je te la passerai. Tu peux compter sur moi. A+

  9. #9
    Membre éclairé Avatar de paradeofphp
    Inscrit en
    Décembre 2005
    Messages
    313
    Détails du profil
    Informations forums :
    Inscription : Décembre 2005
    Messages : 313
    Par défaut
    Bonjour tout le monde,
    A la demande Zoofy, je vous file la procédure qui permet de générer un fichier word à partir des données stockées dans un dataset, j'ai essayé de mettre le maximum de commentaires pour vous facilter la compréhension. Si vous avez des questions, n'hésitez pas.

    J'espère que t'es contente là zoofy


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
                    Dim oWord As Word.Application
                    Dim oDoc As Word.Document
                    Dim oTable As Word.Table
                    Dim oRng As Word.Range
     
     
     
                    ' Start Word and open the document template.
                    oWord = CreateObject("Word.Application")
                    oWord.Visible = True
                    oDoc = oWord.Documents.Add
     
                    ' On récupère le Dataset stoqué en session
                    Dim myDataset As DataSet = New DataSet
     
                    myDataset = CType(Me.ViewState("myDataSet"), DataSet)
                    Dim dv As DataView = myDataset.Tables(0).DefaultView
     
                    ' Insértion du header et footer dans le document Word
                    With oDoc.Sections(1)
                        .Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Text = "Trombinoscope"
                        .Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter
                        .Footers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).PageNumbers.Add()
                    End With
                    ' Mettre le header en gras et centré
                    With oDoc.StoryRanges(Word.WdStoryType.wdPrimaryHeaderStory)
                        .Bold = True
                        .ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter
                    End With
     
     
     
                    For i As Integer = 0 To dv.Count - 1
     
                        Dim k As Integer = 0
     
                        'Insert a (dt.Columns.Count - 2, puisqu'on va pas créer une ligne pour la photo et une ligne pour le chemin de la photo) x 4 table, fill it with data, and change the column widths.
                        oTable = oDoc.Tables.Add(oDoc.Bookmarks.Item("\endofdoc").Range, 1, 4)
                        'On centre le tableau
                        oTable.Rows.Alignment = Word.WdRowAlignment.wdAlignRowCenter
                        'On définit la taille du texte
                        oTable.Range.Font.Size = 9
                        'On définit la police du texte
                        oTable.Range.Font.Name = "Verdana"
                        ' formater la bordure
                        oTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle
                        oTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleDouble
                        ' format la largeurs des  colonnes 
                        'largeur premiere colonne
                        oTable.Columns(1).SetWidth(160, Word.WdRulerStyle.wdAdjustFirstColumn)
                        'largeur deuxième colonne
                        oTable.Columns(2).SetWidth(8, Word.WdRulerStyle.wdAdjustFirstColumn)
                        'largeur troisième colonne
                        oTable.Columns(3).SetWidth(200, Word.WdRulerStyle.wdAdjustFirstColumn)
                        'largeur quatrième colonne
                        oTable.Columns(4).SetWidth(70, Word.WdRulerStyle.wdAdjustFirstColumn)
                        'Espacement
                        oTable.Range.ParagraphFormat.SpaceAfter = 5
     
                        Dim CurrentRow As Integer = 0
     
                        For j As Integer = 1 To dv.Table.Columns.Count
     
    				'On insère l'image                                
    				path = UrlPhoto + dv(i)("ID_PERSONNE") + ".jpg"
                                    oTable.Cell(1, 4).Range.InlineShapes.AddPicture(filename:=path, LinkToFile:=False, SaveWithDocument:=True)
                                    'Affichage vertical de l'image : Centré
                                    oTable.Columns.Item(4).Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalTop
                                    'Affichage horizontal de l'image : Centré
                                    oTable.Cell(1, 4).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter
     
                                    'Taille de l'image
                                    With oDoc.InlineShapes(oDoc.InlineShapes.Count)
                                        .Height = 79   'redimensionne hauteur image
                                        .Width = 67  'redimensionne largeur image
                                    End With
     
                                CurrentRow = CurrentRow + 1
                                If CurrentRow > 1 Then
                                    oTable.Rows.Add()
                                End If
                                'On met les noms de colonnes en gras
                                oTable.Cell(CurrentRow, 1).Range.Font.Bold = True
                                'On écrit : dans la 3ème colonne en gras
                                oTable.Cell(CurrentRow, 2).Range.Text = ":"
                                oTable.Cell(CurrentRow, 2).Range.Font.Bold = True
                                oTable.Cell(CurrentRow, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter
                                'On écrit les noms des champs à afficher
                                oTable.Cell(CurrentRow, 1).Range.Text = myHT.Item(dv.Table.Columns(j - 1).ColumnName)
                                'On écrit les valeurs correspondant à chaque champs
                                If Not dv(i)(j - 1) Is DBNull.Value Then
                                    oTable.Cell(CurrentRow, 3).Range.Text = dv(i)(j - 1)
                                Else
                                    oTable.Cell(CurrentRow, 3).Range.Text = " "
                                End If
     
                           Next
     
                        ' Je fusionne les lignes de la colonne qui contiendra la photo
                        oTable.Cell(Row:=1, Column:=4).Merge(mergeTo:=oTable.Cell(Row:=dv.Table.Columns.Count - 2, Column:=4))
     
                        'Saut de ligne
                        oRng = oDoc.Bookmarks.Item("\endofdoc").Range
                        oRng.InsertBreak(Word.WdBreakType.wdLineBreak)
     
                    Next
     
                    Dim filename As String = "fichier.doc"
                    Dim filepath As String = System.IO.Path.Combine("c:\export\", filename)
                    oDoc.SaveAs(filepath)
                    oDoc.Close()
     
                    oDoc = Nothing        '-- détruire l'objet Document
                    oWord.Quit()          '--On quitte l'application Word
                    oWord = Nothing       '-- détruire l'objet Word
     
                Catch ex As Exception
                    Response.Clear()
                    UniLog.Log(ex, Me)
                    lblMessage.Text = erreur(ex.Message)
                    lblMessage.Visible = True
     
                End Try
            End Sub

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [AC-2010] Génération d'un fichier word depuis une requete
    Par Fiifteen dans le forum Requêtes et SQL.
    Réponses: 1
    Dernier message: 13/06/2015, 15h20
  2. génération d'un fichier word sous vb 2008
    Par kima9 dans le forum VB.NET
    Réponses: 10
    Dernier message: 17/08/2009, 15h16
  3. problème génération fichier Word à partir d'excel
    Par zoum13 dans le forum VBA Word
    Réponses: 3
    Dernier message: 02/02/2007, 13h03
  4. [Word] Génération d'un fichier Word
    Par ami55 dans le forum Bibliothèques et frameworks
    Réponses: 6
    Dernier message: 16/10/2006, 13h12
  5. [VBA-W]Génération de plusieurs fichiers Word
    Par ennamsaoui dans le forum VBA Word
    Réponses: 4
    Dernier message: 10/05/2006, 13h21

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo