Exporting DataGrid to Word
-
quinta-feira, 8 de março de 2012 21:26I am wanting to export a datagridview to word. I am using Visual Studio 2010 Visual Basic. I am just wondering if there is some basic code to reference Word and start using it to create a table and input the data.
Todas as Respostas
-
sexta-feira, 9 de março de 2012 01:17
you want to input a Table or just the information to a word document? What i've posted before mentioned in regards to creating word files was the fact that they are actually archived using the DEFLATE method; a series of mostly XML files packed into an archive using the common .zip compression method. Only with a file extension of perhaps .docx (for latest versions of word).
So if you wanted i'm sure it's possible to use an XML Writer and write out the format of what it looks like to have a Table layout in word, and try to recreate that by packing the data into an XML file before archiving it using the .zip (Base64) DEFLATE compression method.
Edit: The actual document is placed in the word directory of the archive inside the document.xml file. However from the looks of it (keep in mind I haven't strictly analyzed everything to do with word documents I just have the basic idea on how they are integrated with MS word) It looks like there's config xml's on the side that define the particular styling as well for the table. From some time spent as an investigator though i'm sure it wouldn't be too hard to figure out however.
I've taken a screenshot to show you the contents of a .docx (Testing.docx) MS Office Word 2010 file.

Cheers
~Ace
If a post helps you in any way or solves your particular issue, please remember to use the Propose As Answer option or Vote As Helpful
~ "The universe is an intelligence test." - Timothy Leary ~
- Editado AceInfinityMVP sexta-feira, 9 de março de 2012 01:25
-
sexta-feira, 9 de março de 2012 06:23
Hello,
There is a good example of creating and populating a MS-Word table using Open XML as follows (shows how to do tables but is not a drop in section of code to simply use). Before running the project note the path and file name it uses i.e.
Const fileName As String = "C:\temp\AddTable.docx"
If the folder does not exists then either create it or redirect to another folder. If you run the project and get an error (which it will) that does not exactly describe the problem on the following line
Using document = WordprocessingDocument.Open(fileName, True)
It is because the file does not exists. Create a blank MS-Word document and save it according the the const above. Running the project now will create a small table.
In regards to having to create a blank word document, you can use Open XML library to create a new document as needed.
Adding Tables to Word 2010 Documents by Using the Open XML SDK 2.0
If you have not used Open XML before you will need to download it from here. In short for writing code and deploying you need the second download which will install what you need. The first (larger download) download has a tool which will greatly assist with understanding Open XML.
If you decide to go in this direction that in your project add the Open XML library (a single DLL) to your project, select it under project references and select the property window, find the property Copy Local and set this to True. If you do not then the DLL will not be available when distruibuting your project to your customer.
KSG
-
sexta-feira, 9 de março de 2012 12:41
So I need to use XML to write the code to it so it then can be used to make a Word document? What I am wanting to do is basically, when I click "Export to Word" it pulls the information from whatever query is slated to run from a drop down box, opens up Word and throws the table into Word. However, all of my research is showing to use code that is like Dim objApp as Word.Application or something similar.
-
sexta-feira, 9 de março de 2012 14:45
So I need to use XML to write the code to it so it then can be used to make a Word document? What I am wanting to do is basically, when I click "Export to Word" it pulls the information from whatever query is slated to run from a drop down box, opens up Word and throws the table into Word. However, all of my research is showing to use code that is like Dim objApp as Word.Application or something similar.
You can use Office automation or Open XML (my choice especially since this method is safer than using Office automation i.e. if you crash while working with Open XML nothing is left in memory where the same is the opposite with Office automation), the choice is yours but no matter which one is your choice there is no simple code to do this. The following example use Office automation, note the import statements, you need to add as a reference Microsoft.Office.Interop Word.
Create a document with text, ordered list and table w/o borders.
Imports System.Reflection Imports System.IO Imports Word = Microsoft.Office.Interop.Word Imports System.Runtime.InteropServices Imports Microsoft.Office.Interop.Word Class Demo1 Public Shared Sub AutomateWord() Dim WordApp As Word.Application = Nothing Dim Docs As Word.Documents = Nothing Dim Doc As Word.Document = Nothing Dim Paras As Word.Paragraphs = Nothing Dim Para As Word.Paragraph = Nothing Dim ParaRange As Word.Range = Nothing Dim TheFont As Word.Font = Nothing Dim oTable As Word.Table = Nothing Try WordApp = New Word.Application() WordApp.Visible = False Console.WriteLine("Word.Application is started") Docs = WordApp.Documents Doc = Docs.Add() Console.WriteLine("A new document is created") Console.WriteLine("Insert a paragraph") With WordApp.Selection .TypeText("Holding a suspect a gunpoint partial things to do.") .TypeParagraph() .Range.ListFormat.ApplyBulletDefault(WdDefaultListBehavior.wdWord10ListBehavior) .Range.ListFormat.ListOutdent() .TypeText("Do not Move! (Command Voice) ") .TypeParagraph() .TypeText("Do not touch that weapon!") .TypeParagraph() .TypeText("Slowly, raise your hands! (all the way up)") .TypeParagraph() .TypeText("Spread your fingers") .TypeParagraph() .TypeText("Using one hand raise their shirt") .TypeParagraph() .TypeText("Slowly, step away from me!") .TypeParagraph() .TypeText("Slowly, kneel on both knees!") .TypeParagraph() .TypeText("Slowly, cross your ankles!") .TypeParagraph() .TypeText("Slowly, with your hands in front of you where I can see them, lower yourself to the ground…face down, arms out to your sides with the palms up, thumbs to feet…turn your face away from me!") .TypeParagraph() .TypeText("I believe you are armed, Don't Move. If you move you give me reason to shoot you") .TypeParagraph() .Range.ListFormat.ApplyBulletDefault(WdDefaultListBehavior.wdWord10ListBehavior) .TypeText("Demo table below.") .TypeParagraph() End With Console.WriteLine("Creating table") Dim Row As Integer, Column As Integer oTable = Doc.Tables.Add(Doc.Bookmarks.Item("\endofdoc").Range, 3, 5) oTable.Range.ParagraphFormat.SpaceAfter = 6 For Row = 1 To 3 For Column = 1 To 5 oTable.Cell(Row, Column).Range.Text = "r" & Row & "c" & Column Next Next oTable.Rows.Item(1).Range.Font.Bold = True oTable.Rows.Item(1).Range.Font.Italic = True Console.WriteLine("Save and close the document") Dim fileName As String = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) & "\Sample1.docx" Doc.SaveAs(fileName, Word.WdSaveFormat.wdFormatXMLDocument) Doc.Close() Console.WriteLine("Quit the Word application") Console.WriteLine("File: [{0}]", fileName) WordApp.Quit(False) Finally If Not oTable Is Nothing Then Marshal.FinalReleaseComObject(oTable) oTable = Nothing End If If Not TheFont Is Nothing Then Marshal.FinalReleaseComObject(TheFont) TheFont = Nothing End If If Not ParaRange Is Nothing Then Marshal.FinalReleaseComObject(ParaRange) ParaRange = Nothing End If If Not Para Is Nothing Then Marshal.FinalReleaseComObject(Para) Para = Nothing End If If Not Paras Is Nothing Then Marshal.FinalReleaseComObject(Paras) Paras = Nothing End If If Not Doc Is Nothing Then Marshal.FinalReleaseComObject(Doc) Doc = Nothing End If If Not Docs Is Nothing Then Marshal.FinalReleaseComObject(Docs) Docs = Nothing End If If Not WordApp Is Nothing Then Marshal.FinalReleaseComObject(WordApp) WordApp = Nothing End If End Try Console.WriteLine("press a key to terminate...") End Sub End ClassKSG
- Marcado como Resposta Mark Liu-lxfModerator sexta-feira, 16 de março de 2012 09:11
-
segunda-feira, 12 de março de 2012 02:37Moderador
Hi Shadow,
Welcome to the MSDN forum.
If you want to use code to reach your goals, my solution is saving all data in DataGridView to a DataTable, open an existence Word document and save it as a new Table. Here is a sample code, Please make sure add the Microsoft.Office.Interop.Word reference at first.Imports System.Data.OleDb Imports Microsoft.Office.Interop Imports Microsoft.Office.Interop.Word Public Class Form1 Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load 'add your data into datagridview Dim datatabl As New System.Data.DataTable datatabl = DataGridView1.DataSource Dim oWord = New Word.Application With {.Visible = True} Dim oDocs As Word.Document = oWord.Documents.Open("D:\sample.docx") Dim otable As Word.Table otable = oDocs.Tables.Add(oDocs.Bookmarks.Item("\endofdoc").Range, datatabl.Rows.Count + 1, datatabl.Columns.Count) For c = 0 To datatabl.Columns.Count - 1 otable.Cell(1, c + 1).Range.Text = datatabl.Columns(c).ToString Next For r = 0 To datatabl.Rows.Count - 1 For c = 0 To datatabl.Columns.Count - 1 otable.Cell(r + 2, c + 1).Range.Text = datatabl.Rows(r).Item(c).ToString Next Next otable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle otable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle oDocs.Close(SaveChanges:=True) oDocs = Nothing oWord.Quit() oWord = Nothing GC.Collect() GC.WaitForFullGCComplete() End Sub End ClassIf you have any additional questions, please feel free to let me know.
Mark Liu-lxf [MSFT]
MSDN Community Support | Feedback to us
- Marcado como Resposta Mark Liu-lxfModerator sexta-feira, 16 de março de 2012 09:11

