简体   繁体   中英

create word document dynamically in vb.net

I need to create a word document at run time by using vb.net . how can I do that? I created the excel file before, but don't know how use it for word . here is what I use for create the Excel file:

 Sub export_to_excel(recordCount As Integer, DataArray(,) As Object, fileName_Location As String)

    Dim oExcel As Object
    Dim oBook As Object
    Dim oSheet As Object

    ''Start a new workbook in Excel.
    oExcel = CreateObject("Excel.Application")
    oBook = oExcel.Workbooks.Add

    ''Add headers to the worksheet on row 1.
    oSheet = oBook.Worksheets(1)
    '  For i = 0 To headers.Count - 1
    oSheet.Range("A1").Value = "AAA"
    oSheet.Range("B1").Value = "BBB"
    oSheet.Range("C1").Value = "CCC"
    oSheet.Range("A1:C1").Font.Bold = True
    'Next


    ''Transfer the array to the worksheet starting at cell A2.
    oSheet.Range("A2").Resize(recordCount, 3).Value = DataArray

    ''Save the Workbook and quit Excel.
    oBook.SaveAs(fileName_Location)
    oSheet = Nothing
    oBook = Nothing
    oExcel.Quit()
    oExcel = Nothing
    GC.Collect()


End Sub

How can I use something like this code to create word file?

There are a few ways of doing this.

But first of all you are using interop in your example and you can do the same with word. There is a good example of this on MSDN

If you do not need any fonts or anything you can always write to a textfile and use the extention .doc which will open it in word without any problem.

The 3rd and best solution is using Open XML which is the new way of manipulating office documents (extension docX). This format is just plain xml and you can manipulate it as pure text or xml or you can use the open xml sdk which gives you exellent way to manipulate word through a modern interface. This works with office 2007 and up. Documentation is on MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM