Can't Open Excel file using Excel Services in VB.net - sharepoint-2010

I'm performing my first try of tackling Excel Services in SharePoint 2010. I'm trying to open an Excel file that I've uploaded to my shared documents. I have verified that I can manually open the file via the browser using the following url:
http://myserver/Shared%20Documents/Adds2011.xls
However when passing this to the following web routine I receive an error. Here is the routine:
Private Sub OpenExcel(myurl As String)
Dim xlApp As New exServices.ExcelService
xlApp.Credentials = System.Net.CredentialCache.DefaultCredentials
Dim status(10) As exServices.Status
Dim sessionID As String = ""
Try
sessionID = xlApp.OpenWorkbook(myurl, "en-US", "en-US", status)
Dim sheetInfo() As exServices.SheetInfo = xlApp.GetSheetNames(sessionID, status)
Dim cell As Object = xlApp.GetCell(sessionID, sheetInfo(0).Name, 1, 1, True, status)
Catch ex As Exception
Debug.WriteLine(ex.ToString)
End Try
If sessionID <> "" Then
xlApp.CloseWorkbook(sessionID)
End If
End Sub
I receive the following error:
A first chance exception of type 'System.Web.Services.Protocols.SoapException' occurred in System.Web.Services.dll
System.Web.Services.Protocols.SoapException: The workbook that you selected cannot be opened.
The workbook may be in an unsupported file format, or it may be corrupt.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at SMSMInventory.exServices.ExcelService.OpenWorkbook(String workbookPath, String uiCultureName, String dataCultureName, Status[]& status)
at SMSMInventory.LoadSpreadsheetUserControl.OpenExcel(SPFile mySpFile)
Auto-attach to process '[4292] w3wp.exe' on machine 'FS-CHI-SPDEV' succeeded.
A first chance exception of type 'System.Web.Services.Protocols.SoapException' occurred in System.Web.Services.dll
Can anyone tell me what I'm doing wrong?

After contacting Microsoft support, they pointed out my Error:
You cannot open a .xls in the browser (see below URL):
Differences between using a workbook in Excel and Excel Services
http://office.microsoft.com/en-us/excel-help/differences-between-using-a-workbook-in-excel-and-excel-services-HA010021716.aspx
All other Microsoft Office Excel file formats are unsupported, including Office Excel 2007 Macro-Enabled Workbook (.xlsm) and Office Excel 2007 97-2003 Workbook (.xls).
Save as .xlsx and try again.
Using the recommended format solved my problem.

Related

MS Word runs on background and requests documents to be saved even though it is already saved

I have a procedure that creates a PDF file according to an ms word template and its data is retrieved from a database.
It works fine, creates a PDF file perfectly , no run time errors. The problem is that whenever I shut off the computer, ms word prevents the shutdown and if I press cancel ms word shows a message;
The code goes like this;
Dim wordApp As Word.Application
Dim templateBookmarks As Word.Bookmarks
Dim templateName As String
Dim template As Word.Document
'Some other variables for computations
wordApp = CreateObject("Word.Application")
sourceTable = New DataTable
'Some other procs to fill the data table
templateName = "Foo Template.docx"
template = wordApp.Documents.Add(templatePath & templateName)
templateBookmarks = template.Bookmarks
templateBookmarks.Item("sample bookmark").Range.Text = "foo"
'Then fills the table in the template like...
template.Tables(1).Cell(1, 1).Range.Text = dataSource.Rows(0).Item(0)
'Then saves the document as a pdf
Dim saveName As String = "sample file"
template.SaveAs2(savePath & saveName, Word.WdSaveFormat.wdFormatPDF)
I have tried to force garbage collection for the word COM resources, as well as changing the template from an actual document i.e. docx to a word template .dotx. I also tried the method Quit() but it only shows the ms word message much earlier. This is the first time I needed to use interop so pardon if I don't have much idea about it.
The files I needed are saved, the only problem is the ms word message and unsaved and unnecessary files e.g. Document1,Document2,Document3 that seems to be created aside from the required PDF
Use the Document.Close method which closes the specified document after saving files using the PDF file format. It allows specifying the SaveChanges parameter which specifies the save action for the document. Can be one of the following WdSaveOptions constants: wdDoNotSaveChanges, wdPromptToSaveChanges, or wdSaveChanges.
On Error GoTo errorHandler
ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
errorHandler:
If Err = 4198 Then MsgBox "Document was not closed"

Close Excel Workbook If Test for Open Returns False

I've constructed a VB.Net application which loads data into an Excel spreadsheet. The application works fine, but I've added a functionality to test whether the workbook is Open, and if so, the application terminates. Otherwise, if the workbook Is Not Open, then the user can proceed to fill information in the application. My issue is that when is when the worksheet is not open, my code blows up due to the workbook being "somehow opened." I need to close any processes, then proceed. Here's my code for checking if the workbook is open or not:
1st, my module, which sets up the a Boolean check:
Public Module ExcelCheck
Public Function Test(ByRef sName As String) As Boolean
Dim fs As FileStream
Try
fs = File.Open(sName, FileMode.Open, FileAccess.Read, FileShare.None)
Test = False
Catch ex As Exception
Test = True
End Try
End Function
End Module
Then my handler for a button on the form that does the check:
Private Sub btnOpenFileCheck_Click(sender As Object, e As EventArgs) Handles btnOpenFileCheck.Click
'Evaluate if the workbook is being used:
Dim bExist As Boolean
bExist = Test("\\netshareA\c$\Users\Pete\Desktop\TestUnits\Machines.xls")
If bExist = True Then
MessageBox.Show("The file is open... Please try again later.", "EXCEL FILE IN USE: Abort", MessageBoxButtons.OK)
Me.Close()
Else bExist = False
MessageBox.Show("The file is NOT open... You may proceed...", "EXCEL FILE NOT OPEN", MessageBoxButtons.OK)
Dim xlOpenItem As New Excel.Application
Dim xlOpenWB As Excel.Workbook = xlOpenItem.Workbooks.Open("\\netshareA\c$\Users\Pete\Desktop\TestUnits\Machines")
xlOpenWB.Close(SaveChanges:=False, Filename:="\\netshareA\c$\Users\Pete\Desktop\TestUnits\Machines.xls", RouteWorkbook:=False)
txtCPUSerial.Focus()
End If
End Sub
What happens when the book isn't open is the proper dialog to continue runs via the illustration:
But then an Excel dialog appears saying the following:
'\\netshareA\c$\Users\Pete\Desktop\TestUnits\Machines.xls'
is currently in use. Try again later.
Then, it finally blows up and I have the line of referenced:
Dim xlOpenWB As Excel.Workbook = xlOpenItem.Workbooks.Open("\\netshareA\c$\Users\Pete\Desktop\TestUnits\Machines")
My logic is that I need to have an open instance of an Excel object, then close that instance in order to terminate any inadvertent running process. I actually open the workbook in another submit handler, with the Excel objects and variables set well, but that's not my issue. How can I smoothly make sure the workbook object is closed here as as to not throw an exception that it isn't?
After much tinkering around, I've found out exactly what my problem was - I didn't close out the opened file stream:
Public Module ExcelCheck
Public Function Test(ByRef sName As String) As Boolean
Dim fs As FileStream
Try
fs = File.Open(sName, FileMode.Open, FileAccess.Read, FileShare.None)
Test = False
fs.Close() 'This closes out the initially opened file stream for checking.
Catch ex As Exception
Test = True
End Try
End Function
End Module
I eventually came back to the module and wondered what happens if I just close out and use fs.Close() and it did the trick. No more blow ups! Hope this helps someone else whom might struggle with a similar file stream issue.

How do I copy a file to the clipboard and paste it somewhere else?

I have a listview with small thumbnails of images.
Each image has a tag with it's full path in it.
With a rightclick menu the user can click COPY.
Then this code is excecuted:
Dim selectedfile As String
selectedfile = Me.lvFotos.SelectedItems(0).Tag
Dim dataobj As New DataObject(DataFormats.FileDrop, selectedfile)
Clipboard.Clear()
Clipboard.SetDataObject(dataobj)
Now when I click on my desktop to paste the file I get an exception error in VS2010:
An exception of type 'System.Runtime.InteropServices.COMException' occurred in System.Windows.Forms.dll and wasn't handled before a managed/native boundary
Additional information: Invalid FORMATETC structure (Exception from HRESULT: 0x80040064 (DV_E_FORMATETC))
What am I doing wrong here?
rg.
Eric
You could use directly My.Computer.FileSystem.CopyFile.
Dim source As String = lvFotos.SelectedItems(0).Tag
Dim destination As String = My.Computer.FileSystem.SpecialDirectories.Desktop & from.Substring(from.LastIndexOf("\"))
My.Computer.FileSystem.CopyFile(source, destination)
Using the code from John Smith at Copying a File To The Clipboard:
Dim f() As String = {"C:\temp\Folder.jpg"}
Dim d As New DataObject(DataFormats.FileDrop, f)
Clipboard.SetDataObject(d, True)
(Tested as working in VS2013 on Windows 7 x64.)
Note that you have to pass an array of strings representing your filename(s), so you could allow the user to gather several items before pasting, if you wanted to.
The true in Clipboard.SetDataObject allows the data to remain on the clipboard when you exit the program, so if the user were to select a file and exit before pasting, they would not have lost their selection.
Found what I was doing wrong.
At first I had tried it with the name of the file in an array, but that gave the same error.
Now I have it like this:
Dim selectedfile(0) As String
selectedfile(0) = Me.lvFotos.SelectedItems(0).Tag
Dim dataobj As New DataObject
dataobj.SetData(DataFormats.FileDrop, True, selectedfile)
Clipboard.Clear()
Clipboard.SetDataObject(dataobj, True)
The difference is in the line with SETDATA.
By setting the second argument to TRUE in SetData and also in the SetDataObject, it started to work.

system.diagnostics.process will not open Excel file without Excel open first

I have a VB.Net application in which I have a general method to open documents that exist on the local drive using system.diagnostics.process.
Public Shared Function OpenFileWithProcess(ByVal lsFileNameWithPath As String, Optional ByVal lPrintOption As PrintOutputOption = PrintOutputOption.Preview)
Try
Select Case lPrintOption
Case PrintOutputOption.Preview
Dim P As System.Diagnostics.Process
P = Process.Start(lsFileNameWithPath)
If Not P Is Nothing Then
Dim handle As IntPtr = P.Handle
SetForegroundWindow(handle)
End If
Case PrintOutputOption.Print
Dim Proc As New Process
Proc.StartInfo.FileName = lsFileNameWithPath
Proc.StartInfo.UseShellExecute = True
Proc.StartInfo.Verb = "Print"
Proc.Start()
End Select
Catch ex As Exception
If oSQL.Key_Developer Then
Stop
End If
Throw ex
End Try
End Function
On some computers that have Windows8 and OFfice2010, this method will not open an Excel file without Excel being open first. Instead it will error with "Run-Time Error 2147467259 (80004005). An error occurred in sending the command to the application".
If Excel is open prior to the method call, then the file opens just fine.
Some additional environment info:
- VB.NET application compiled to .Net Framework 4
- Application is deployed on Windows 7, 8 and 8.1
I could trap for the error and try to start the process again using the Excel session that hangs open after the error but I'm wondering if someone can tell me or help me figure out what is going on here.
Thank you for your time.

Trying to open a excel template and rename or save to new location

I get the following error message when I try the following:
Dim XL As New Microsoft.Office.Interop.Excel.Application
XL.Visible = True
XL.Workbooks.Open(XLTemplatePath)
XL.SaveWorkspace(XLSaveReportPath)
XL.Workbooks.Close()
XL.Workbooks.Open(XLSaveReportPath)
"Excel cannot open the file 'ContactReports.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."
What I would like to do is Open a excel file that is the XLTemplatePath and the either rename or save the file at the XLSaveReportPath and then use that renamed/saved file to fill the report out.
I am using Visual Studio 2008 in VB.NET
The saveworkspace method does not save the file. It save the workspace in the format xlw even though you are naming the file you are saving the workspace in as xls. When you try and open the document you are opening a worspace and you recieve the error.
To have this work correctly you need to get the workbook so you can sabe the workbook instead of the application.
Dim XL As New Microsoft.Office.Interop.Excel.Application
Dim XLWorkbook as new Microsoft.Office.Interop.Excel.Workbook
XL.Visible = True
XLWorkbook = XL.Workbooks.Open(XLTemplatePath)
XLWorkbook.SaveAs(XLSaveReportPath)
XL.Workbooks.Close()
XL.Workbooks.Open(XLSaveReportPath)
Should do the trick. Let us know if you have any problems.
Heare are the MSDN refrences for your review:
Application.SaveWorkspace Method
Workbook.SaveAs Method
I have used the following Visual Basic code to work with Microsoft Excel 2003. The key difference (other than Visual Basic 6 vs VB.Net) is that I use the SaveAs method of the Workbook object rather than the SaveWorkspace method.
Set ExcelApp = CreateObject("Excel.Application")
ExcelApp.Visible = True
Set ExcelDoc = ExcelApp.Workbooks.Open(FileName:=XLTemplatePath, ReadOnly:=True)
ExcelDoc.SaveAs(FileName:=XLSaveReportPath)
ExcelDoc.Close(SaveChanges:=False)
ExcelApp.Workbooks.Open(FileName:=XLSaveReportPath)