.NET read word/excel documents without Microsoft.Office.Interop - vb.net

I'm trying to open a doc file under VB.NET, I found a very simple way to do it using word:
For example:
Dim doc As Word.Document
Dim wordApp As New Word.Application
Dim allText As String
Try
doc = wordApp.Documents.Open("C:\marti.doc")
allText = doc.Range.Text()
doc.Close()
RichTextBox1.Text = allText
Catch
'error
End Try
(More detailed info: http://support.microsoft.com/kb/316383)
This could work, but it need to open Microsoft Word window to handle it. I need to use it without Word installed. So I need a Library which can open doc/excel files.
Do you know a good Library that can do this?
I found this library:
http://bytescout.com/download/trial/documentsdk.html
Have you tried this?

The recommended way of interacting with Office files is through the Office OpenXML library. You can get it here.
If you are using Microsoft Office 2003, you can load and save documents in Open XML if you have installed the Microsoft Office Compatibility Pack for Word, Excel, and PowerPoint 2007 File Formats. You can download the compatibility pack and find more info here.
This is an example method to gather the content of the document:
Private Shared Function GetWordDocContent(strDoc As String) As String
Dim stream As Stream = File.Open(strDoc, FileMode.Open)
Dim wordprocessingDocument__1 As WordprocessingDocument = WordprocessingDocument.Open(stream, True)
Dim body As Body = wordprocessingDocument__1.MainDocumentPart.Document.Body
Dim content As String = body.InnerText
wordprocessingDocument__1.Close()
Return content
End Function
Another example here.

for handling docx file you can try NPOI or DocX
for the old word format (.doc) I've tried Syncfusion DocIO components, but i prefer to use word automation with NetOffice, much better than the interop

Related

How can I reference a .dotx resource in VB.NET? (Visual Studios Pro)

I have a program that requires the use of a file with the extension .dotx. Right now I have it as a resource in the solution. With the following code, instead directly using "C:\letterhead.dotx" I want to use the file I have as an 'Embedded Resource'. I tried the following.
Dim oWord As Word.Application
Dim oDoc As Word.Document
oWord = CreateObject("Word.Application")
oWord.Visible = False
'Works:
oDoc = oWord.Documents.Add("C:\Letterhead.dotx")
'Does not work:
oDoc = oWord.Documents.Add(My.Resources.Letterhead)
'Does not work:
oDoc = oWord.Documents.Add(My.Resources.ResourceManager.BaseName & "\Letterhead.dotx")
I am aware that all of those are returning the wrong values and not what I want. I just don't want to force anyone, using this, to put the Letterhead file in a specific place on their computer before running it. I'm sure there's a simple solution, I just don't know it.
Solution:
For all of those (just me) that are also having this problem, all you have to do is the following to write the embedded file to C:\ -
Try
File.WriteAllBytes("C:\Letterhead.dotx", My.Resources.Letterhead)
Catch ex As Exception
MessageBox.Show("Failed to write to C:\", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
You can absolutely store a Word document in a .NET assembly in an embedded resource, and it's fairly trivial to extract it. However, if you want to open a Word document, the steps would be:
Extract the embedded resource to a bytestream
Write the bytestream to a disk (temp folder, perhaps?) as a "doc" or "docx" file
Open that file from disk with Word
...which is quite a bit more work than just including a Word document with the software. Unless you have a very compelling reason to do this with an embedded resource, I would just include the Word document with the application.
If you want some more details, check out Aseem Gautam's answer to this question.

Convert PDF to string using acrobat dlls

I am working on a vb.net project. I am trying to convert the content of a pdf file to string using acrobat dlls (cannot use other 3 rd party dlls). Below is my code, when I run the program I am getting the following error: "Retrieving the COM class factory for component with CLSID, failed due to the following error: 80040154 Class not registered". I did some research and found out that I have to install the full version of acrobat standard or professional version. Not only that the full version of acrobat must also be installed in all the user machines that the program runs.
Can anyone tell me if this is true and suggest how to fix the class not registered error?
Sub Main()
Dim s As String
Dim sSourceFile As String
sSourceFile = "P:\Report images\DevReports\New Folder\UM-STD-Approval_154.pdf"
Dim oSourceFileInfo As New System.IO.FileInfo(sSourceFile)
Dim st As New AcroPDDoc
st.Open(sSourceFile)
s = GetText(st)
Dim oAcroApp As Acrobat.CAcroApp = New Acrobat.AcroApp
Dim oAcroAvDoc As Acrobat.CAcroAVDoc = New Acrobat.AcroAVDoc
Dim oAcroPDDoc As Object = Nothing
If oAcroAvDoc.Open(sSourceFile, "") Then
'Set PDDoc object and save the file.
oAcroPDDoc = oAcroAvDoc.GetPDDoc()
' oAcroPDDoc.Save(1, sOutputFile)
Else ' Document FAILED to open.
MsgBox("Cannot open ")
End If
oSourceFileInfo = Nothing
oAcroApp.CloseAllDocs()
oAcroPDDoc = Nothing
oAcroAvDoc = Nothing
oAcroApp.Exit()
oAcroApp = Nothing
End Sub
Apologies for the obvious answer but you've kind of answered your own question already.
Adobe Reader is a free application with a very limited interface allowing automation; in practice it's limited to the point where you can display a PDF file and navigate through it (to some extent).
For full features automation (like what I think you are looking for) you will need to install the full Adobe Acrobat. And yes, any system you run this on will also need to have Adobe Acrobat installed.
Now, there are probably libraries out there (including libraries from Adobe or containing Adobe technology inside) that will allow you to embed the functionality you are looking for in your application, but those too will not be free...

Create Word document on server and offer Client as Download

Hi iam creating a Word document like:
Dim oApp As Word.Application
Dim oDoc As Word.Document
oApp = CreateObject("Word.Application")
oDoc = oApp.Documents.Add
Dim rng As Word.Range = oDoc.Range(0, 0)
rng.Font.Name = "Verdana"
rng.Font.Size = 16
.......
...............
oApp.Visible = True
oDoc = Nothing
oApp = Nothing
This works perfect on my local machine. But if i put my Code on Webserver it of course does not work.
My Question is: What i have to do, that the Word document gets created on the server and offer the created document to the client as Download.
Can someone help me with that? Thanks!!
I think they way you are currently doing this requires Microsoft Word (Or at least the Interop components) to be present on the server to allow this.
Perhaps a better approach would be to create a PDF on the fly and offer that to the client
alternatively perhaps this approach would work or this?
EDIT:
Also please see how-to-generate-word-documentdoc-docx-in-asp-net
EDIT:
This code snippet will allow you to stream the file down to the client
using (MemoryStream mem = new MemoryStream())
{
// Create Document
using (<declare document>))
{
//create your document here
// Stream it down to the browser
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
Response.AppendHeader("Content-Disposition", "attachment;filename=HelloWorld.docx");
mem.Position = 0;
mem.CopyTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
Just saw this...
I have managed to get Word running on a server (Apache). You must run Apache under a user account that can run Word. Also if you use Office 32-bit you must run Apache 32-bit. Only one instance of Word runs at one time. However, Word can have multiple documents open at the same time. I developed an addin that I put in Word's startup directory so it is available for each document. In the AutoExec macro I trigger the code that reads a job queue and generates the document. All this is run from the web using AJAX and PHP.

Not sure how to use IsolatedStorage

I want to create a notes app for Windows Phone 7 using Visual Basic. I have read a few tutorials but they are all suited for C# not VB. Basically, I have a main page and a page to add notes. Once the user types out a note on the add notes page, the title of that note appears on the main page. I also want the user to be able to select that title and it will display the note. I have done a bit of research and I know I will need to use isolated storage (not sure how to implement it in VB) to save the notes. I think I will also need a list box that will store the title of the notes. I am not asking for someone to just give me code, I am asking for some tutorials regarding this in VB or any pointers or general help on acheiving this. Thanks
All the code samples on MSDN are available in both C# and VB. See http://msdn.microsoft.com/en-us/library/ff431744(v=vs.92).aspx
The Model-View-ViewModel Sample (under Common Application Development Tasks) is probably a good place for you to start.
The link to download the VB code is http://go.microsoft.com/fwlink/?LinkId=229339
You are correct that you will need to use IsolatedStorage if you're wanting to write the notes to the phone (and not the cloud somewhere). Here is a link to a blog entry that has a class (in Visual Basic) that has some helper methods that will give you some similiar methods to VB.Net traditional methods (like ReadAllText, WriteAllText). It may be what you want for the file system reading/writing (but at a minimum will get you started with Isolated Storage).
http://www.blakepell.com/2012-03-07-wp7-file-helpers
Isolated Storages
Isolated storage is used to store local files such as text files, images, videos etc on the Windows Phone. Each app is assigned a specific isolated storage and is exclusive ONLY to that app. No other app is able to access your apps isolated storage.
A lot can be read from here All about Windows Phone Isolated Storage
Before you begin you will need to import IsolatedStorage to your project.
Imports System.IO
Imports System.IO.IsolatedStorage
Creating Folders
This creates a directory in your apps isolated storage. It will be called "NewFolder"
Dim myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
myIsolatedStorage.CreateDirectory("NewFolder")
You can create folders inside folders inside folders like so:
myIsolatedStorage.CreateDirectory("NewFolder/NewFolder1/NewFolder2/NewFolder3")
To delete a folder:
myIsolatedStorage.DeleteDirectory("NewFolder")
A good practice when creating and deleting folders is to add a Try Catch statement around the folder creation method so if there is an exception you or the user will be notified as to why it occurs e.g. the folder not existing therefore cannot be deleted or the folder existing therefore needing to be replaced etc. The example below shows a basic function in creating a folder with a Try Catch statement.
Public Sub CreateDirectory(directoryName As String)
Try
Dim myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
If Not String.IsNullOrEmpty(directoryName) AndAlso Not myIsolatedStorage.DirectoryExists(directoryName) Then
myIsolatedStorage.CreateDirectory(directoryName)
End If
' handle the exception
Catch ex As Exception
End Try
End Sub
To use it you can do:
Me.CreateDirectory("NewFolder")
For the deletion method:
Public Sub DeleteDirectory(directoryName As String)
Try
Dim myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
If Not String.IsNullOrEmpty(directoryName) AndAlso myIsolatedStorage.DirectoryExists(directoryName) Then
myIsolatedStorage.DeleteDirectory(directoryName)
End If
' handle the exception
Catch ex As Exception
End Try
End Sub
And to use it:
Me.DeleteDirectory("NewFolder")
Creating Files
You can create an empty file like this:
Dim myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Dim writeFile As New StreamWriter(New IsolatedStorageFileStream("NewFolder\SomeFile.txt", FileMode.CreateNew, myIsolatedStorage))
To delete the file:
myIsolatedStorage.DeleteFile("NewFolder/SomeFile.txt")
Like before, a good practise when it comes to creating files is to always check if the directory you are writing to or deleting exists.
You can do something like:
Try
Dim myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Dim writeFile As StreamWriter
If Not myIsolatedStorage.DirectoryExists("NewFolder") Then
myIsolatedStorage.CreateDirectory("NewFolder")
writeFile = New StreamWriter(New IsolatedStorageFileStream("NewFolder\SomeFile.txt", FileMode.CreateNew, myIsolatedStorage))
Else
writeFile = New StreamWriter(New IsolatedStorageFileStream("NewFolder\SomeFile.txt", FileMode.CreateNew, myIsolatedStorage))
End If
' do something with exception
Catch ex As Exception
End Try
Saving and Reading Text Files
To save a text file with your content you can do something like:
Dim myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Using writeFile As New StreamWriter(New IsolatedStorageFileStream("myNote.txt", FileMode.Create, FileAccess.Write, myIsolatedStorage))
Dim someTextData As String = "This is some text data to be saved in a new text file in the IsolatedStorage!"
writeFile.WriteLine("note data")
writeFile.Close()
End Using
To read the contents of the Text File:
Dim myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Dim fileStream As IsolatedStorageFileStream = myIsolatedStorage.OpenFile("myFile.txt", FileMode.Open, FileAccess.Read)
Using reader As New StreamReader(fileStream)
TextBlock.Text = reader.ReadLine()
End Using
I've provided you with some of the basics of the Windows Phone Isolated Storage and how to use it but I highly suggest that you read more about it at Here

Download file in VB.NET 2010

I have looked almost everywhere on the internet and I cannot find a way to download a file from the internet into a specific folder that works with VB.NET 2010. I would like to download a file called, for instance, example.txt, and download it into, for example, %HOMEDRIVE%%HOMEPATH%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup so that it will run automatically at system startup. All help is appreciated
Guessing something based on...
Using webClient = New WebClient()
Dim bytes = webClient.DownloadData("http://www.google.com")
File.WriteAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyFileName.ext"), bytes)
End Using
As for the startup, VB.NET has a pretty ease way to add Registry keys...
My.Computer.Registry.SetValue
To set something like HKEY_CURRENT_USER\Software\Microsoft\CurrentVersion\Run
UPDATE
How to: Create a Registry Key and Set Its Values in Visual Basic
http://msdn.microsoft.com/en-us/library/cy6azwf7(v=VS.100).aspx
I would suggest using WebClient.DownloadFile. Use Environment.SpecialFolder.Startup to get the path to save the file.
Sub Main()
Using wc As New WebClient()
Dim startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
wc.DownloadFile("http://MyDomain.com/MyFile.txt", Path.Combine(startupPath, "test.txt"))
End Using
End Sub