Importing data from excel sheet - sql

Using MS VS 2013 and SQL server 2012
I am writing a console app to copy some data from excel into an SQL table. I am not getting very far. The code below opens the file then after 2-3 seconds I get an error.
There error is -
Additional information: Unable to cast COM object of type
'System.__ComObject' to interface type
'Microsoft.Office.Interop.Excel.Worksheet'. This operation failed
because the QueryInterface call on the COM component for the interface
with IID '{000208D8-0000-0000-C000-000000000046}' failed due to the
following error: No such interface supported (Exception from HRESULT:
0x80004002 (E_NOINTERFACE)).
Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop
Imports System.Data.SqlClient
Imports System.IO
Module Module1
Sub Main()
Dim xlApp As Application
Dim xlWorkBookSrc As Excel.Workbook
Dim xlWorkBookDest As Excel.Workbook
Dim xlWorkSheetSrc As Excel.Worksheet
Dim xlWorkSheetDest As Excel.Worksheet
xlApp = New Excel.Application
xlApp.Visible = True
xlApp.DisplayAlerts = False
xlWorkSheetSrc = xlApp.Workbooks.Open("Folder path")
xlWorkSheetSrc = xlWorkBookSrc.Worksheets("Spectrometer")
End Sub
End Module
As the file opens ok I am not sure why I then get the error. The excel sheet is a .xls but I also tried with an .xlsx and get the same result.
Any ideas

This line:
xlWorkSheetSrc = xlApp.Workbooks.Open("Folder path")
..is failing because its defines xlWorkSheetSrc as a Worksheet and xlApp.Workbooks.Open is returning a Workbook, which is not a Worksheet. Change it to:
xlWorkBookSrc = xlApp.Workbooks.Open("Folder path")
..and it should be OK.

Refer Example given in Importing Exporting Excel Files
This Example in VB.NET and I tested and it's working fine in my PC.
I suggest to use OleDB (ADO.NET) to import excel data and export that data to SQL server (using SqlConnection (ADO.NET)).
Excel To SQL Server

Related

COM Error trying to create Excel.Application object

Working from Visual Studio 2013 to create a new program involving excel. Done this before in earliere excel versions, but cannot get it to work now.
Trying to create the excel application object throws an error (however an excel process is started when I look in the task manager). We're using Office 365 with Excel 2016. I have uninstalled Office and made a complete new installation, but still having the same error.
Having a vb .net windows project. I haved added a reference by choosing COM - Type Libraries - and added Microsoft Excel 16.0 Object Library (version 1.9).
Code is like this:
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim appXL As Excel.Application
Dim wbXl As Excel.Workbook
Dim shXL As Excel.Worksheet
Dim raXL As Excel.Range
' Start Excel and get Application object.
appXL = CreateObject("Excel.Application")
appXL.Visible = True
appXL = CreateObject("Excel.Application")
throws error :
An unhandled exception of type 'System.InvalidCastException' occurred in WindowsApplication3.exe
Additional information: Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}' failed due to the following error: Interface not registered (Exception from HRESULT: 0x80040155).
I have checked registry editor in HKEY_CLASSES_ROOT - typelib and found the IID {000208D5-0000-0000-C000-000000000046}. It looks like this:
TypeLib (Default) REG_SZ {00020813-0000-0000-C000- 000000000046}
Version REG_SZ 1.9
Any help will be much appreciated. Thanks.

Using SSIS to run an Excel macro

I have an SSIS package that runs a bunch of SSRS reports and saves them in a folder as .xlsx files. I also have an Excel file with a macro that goes through each .xlsx file saved, consolidates into one file, formats and saves in another folder.
Right now this is a 2 step process, so my goal is to make it just 1 step. To do that I'm trying to add a Script Task to the end of my SSIS package to open my Excel file with the macro and run it.
I have scoured the web looking for solutions for this and found many that seem to work for people, but aren't working for me. Specifically, I'm using the code from this site.
Now when I populate the code, add my reference to Microsoft Excel 15.0 Object Library and add the Imports Microsoft.Office.Interop to the top of my script, I'm getting errors on some of the code. Please see screenshot below:
The error I'm getting is:
Reference to class 'ApplicationClass' is not allowed when its assembly is linked using No-PIA mode.
I found this site where someone seemed to have a similar issue, but it didn't help me with mine.
Is there something I'm doing wrong in the script somewhere? See below for the script itself.
' Microsoft SQL Server Integration Services Script Task
' Write scripts using Microsoft Visual Basic 2008.
' The ScriptMain is the entry point class of the script.
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports Microsoft.Office.Interop
_
_
Partial Public Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
Enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
End Enum
' The execution engine calls this method when the task executes.
' To access the object model, use the Dts property. Connections, variables, events,
' and logging features are available as members of the Dts property as shown in the following examples.
'
' To reference a variable, call Dts.Variables("MyCaseSensitiveVariableName").Value
' To post a log entry, call Dts.Log("This is my log text", 999, Nothing)
' To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, True)
'
' To use the connections collection use something like the following:
' ConnectionManager cm = Dts.Connections.Add("OLEDB")
' cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;"
'
' Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
'
' To open Help, press F1.
Public Sub Main()
Dim oExcel As Excel.ApplicationClass = Nothing
Dim oBook As Excel.WorkbookClass = Nothing
Dim oBooks As Excel.Workbooks = Nothing
Try
'Start Excel and open the workbook.
oExcel = CreateObject("Excel.Application")
oExcel.Visible = False
oBooks = oExcel.Workbooks
oBook = oBooks.Open(Dts.Variables("StrFilePath").Value.ToString()) ' Change your variable name here.
'Run the macros.
oExcel.Run("Format") ' Change the name of your Macro here.
'Clean-up: Close the workbook and quit Excel.
oBook.Save()
oExcel.Quit()
Dts.TaskResult = ScriptResults.Success
Finally
If oBook IsNot Nothing Then System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook)
If oBooks IsNot Nothing Then System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks)
If oExcel IsNot Nothing Then System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel)
oBook = Nothing
oBooks = Nothing
oExcel = Nothing
End Try
End Sub
End Class
Any help/advice is greatly appreciated!

Previous Excel instance not getting through IIS

I am using VB.NET to open the Excel files but dont want to create excel object every time.
My code is working perfectly in debug mode, but after publish, it never gets the existing instances and always create new instances which we can see from Task Manager. Here is my code which always returns false in published mode.
My OS is Windows Server 2008. Please guide how to solve this.
Function IsExcelRunning() As Boolean
Dim xlApp As Excel.Application
On Error Resume Next
xlApp = GetObject(, "Excel.Application")
IsExcelRunning = (Err.Number = 0)
MyHelper.writeLog("Excel Instance found=" & IsExcelRunning)
xlApp = Nothing
Err.Clear()
End Function
Here is how I call.
If IsExcelRunning() Then
excelApp = GetObject(, "Excel.Application")
Else
excelApp = Server.CreateObject("Excel.Application")
End If
We used to use Excel Interop and I remember it always being difficult to work with (clunky.) Due to the Interop opening an Excel process and not closing it every time you use it, makes it difficult to work with.
The Interop opens Excel automatically, so all we needed to do was close it. This is what we used to use to kill the Process. Replace YourProcessName with Excel.exe.
Dim proc As System.Diagnostics.Process
Dim info As ManagementObject
Dim search As New ManagementObjectSearcher("SELECT ProcessId FROM Win32_process WHERE caption = 'YourProcessName'")
For Each info In search.Get()
Dim TheString As String = info.GetText(TextFormat.Mof).ToString
proc = System.Diagnostics.Process.GetProcessById(Mid$(TheString, _
(Len(TheString) - 8), 4))
proc.CloseMainWindow()
proc.Refresh()
If proc.HasExited Then GoTo NoKill
proc.Kill()
NoKill:
Next
You'll need to import
Imports System.Management
You'll also need to add the reference 'System.Management' to your project.
See: http://msdn.microsoft.com/en-us/library/vstudio/wkze6zky.aspx for adding a reference to a project.
If you can rather work with CSV, I would suggest you try to. If you are creating the Excel file yourself, try to find a report creator that let's you create / export to Excel. You'll save yourself a lot of time in the long run.

vb.net "PasteSpecial method of Range class failed"

I'm trying to write an application in VB.net that assembles an Excel Workbook by wisely coping cells from another opened Workbook. [Note: as for now, the two workbooks are opened within the same Excel application - Originally I was using two different Excel instances, but only later I realized that the PasteSpecial between two Instances behaves differently]
I'm using Visual Studio 2012, Excel 2007 and I'm including Microsoft Excel 12.0 Object Library in the project references
The code is something like that:
Dim appXL As Excel.Application
Dim wbXLsource As Excel.Workbook
Dim wbXLtarget As Excel.Workbook
''with two different buttonclick event handlers
''I assign wbXLsource and wbXLtarget
''the full code is omitted
...
wbXLsource = appXL.Workbooks.Open(strFileNameAndPath)
...
...
wbXLtarget = appXL.Workbooks.Add
...
''I use a third button handler for the
''Copy and PasteSpecial Operations
Private Sub btnAppendWorksheet_Click(sender As Object, e As EventArgs) _
Handles btnAppendWorksheet.Click
Dim shXLtar As Excel.Worksheet
Dim shXLsou As Excel.Worksheet
shXLtar = wbXLtarget.ActiveSheet
shXLtar.Cells.Clear()
shXLsou = wbXLsource.ActiveSheet
shXLsou.Range("A1:H433").Copy()
Try
shXLtar.Range("A1:H433").PasteSpecial(Excel.XlPasteType.xlPasteAll, False, False) ''Paste special Format:=
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
The PasteSpecial method throws the exception "PasteSpecial method of Range class failed".
What is strange is that the same code originally worked within two workbooks that run in different Excel instances [At that time I had appXLtarget and appXLsource].
Needless to say that I tried all the possible combinations of "Selection", "Activate" in any part of the code: eg between Copy and PasteSpecial etc etc.
Probably there is something really coarse that I'm missing <- I'm new of VB.net
Thanks for any help and Best Regards!
If you are new in VB.Net, you should first do research about OptionStrict. With optionStrict set to ON, VS won't compile your code...
Replace
shXLtar.Range("A1:H433").PasteSpecial(Excel.XlPasteType.xlPasteAll, False, False)
With
shXLtar.Range("A1:H433").PasteSpecial(Excel.XlPasteType.xlPasteAll,Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone,False, False)
or
shXLtar.Range("A1:H433").PasteSpecial(Excel.XlPasteType.xlPasteAll)
Hope this helps.

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)