March 4, 2009

Vb.net - Generate word file from world file template

Private Sub GenrateWord()
Try
Dim openFileDialog As New OpenFileDialog
Dim a() As Object = {}
openFileDialog.FileName = System.AppDomain.CurrentDomain.BaseDirectory() & "Final.doc"
Dim filename As Object = openFileDialog.FileName
Dim wordType As Type = Type.GetTypeFromProgID("Word.Application")
Dim wordApplication As Object = Activator.CreateInstance(wordType)
wordType.InvokeMember("Visible", Reflection.BindingFlags.SetProperty, Nothing, wordApplication, New Object() {False})
Dim wordDocuments As Object = wordType.InvokeMember("Documents", Reflection.BindingFlags.GetProperty, Nothing, wordApplication, a)
Dim wordDocument As Object = wordType.InvokeMember("Open", Reflection.BindingFlags.InvokeMethod, Nothing, wordDocuments, New Object() {filename})
Dim activeWindow As Object = wordDocument.[GetType]().InvokeMember("ActiveWindow", Reflection.BindingFlags.GetProperty, Nothing, wordDocument, Nothing)
Dim selection As Object = activeWindow.[GetType]().InvokeMember("Selection", Reflection.BindingFlags.GetProperty, Nothing, activeWindow, Nothing)
selection.[GetType]().InvokeMember("WholeStory", Reflection.BindingFlags.InvokeMethod, Nothing, selection, Nothing)
selection.[GetType]().InvokeMember("Copy", Reflection.BindingFlags.InvokeMethod, Nothing, selection, Nothing)
wordDocument.[GetType]().InvokeMember("Close", Reflection.BindingFlags.InvokeMethod, Nothing, wordDocument, Nothing)
wordApplication.[GetType]().InvokeMember("Quit", Reflection.BindingFlags.InvokeMethod, Nothing, wordApplication, Nothing)
Dim data As IDataObject = Clipboard.GetDataObject()
Dim text As String = data.GetData(DataFormats.Rtf, True).ToString()

Dim fs As New FileStream(strSaveFile, FileMode.Create, FileAccess.Write)
'declaring a FileStream and creating a document file named file with access mode of writing
Dim s As New StreamWriter(fs)
'creating a new StreamWriter and passing the filestream object fs as argument
text = text.Replace("{TODate}", System.DateTime.Now.Year().ToString())
s.Write(text)
'writing text to the newly created file
s.Close()
MessageBox.Show("Process has been done Successfully.", Msgboxtitle, MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message, Msgboxtitle, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub

No comments:

Post a Comment