how to export sql table data into excel worksheet? - sql

I have this table that I want to export its data into my excel file.
so far I've tried every topic here but nothing worked.
I've tried these 2:
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\excel\testing.xls;',
'SELECT * FROM [newStart$]') select * from OutputResult
insert into OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 8.0;Database=D:\excel\testing.xls;',
'SELECT * FROM [newStart$]') select * from OutputResult
when I run it with jet I'll get this error:
OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "(null)" returned message "The Microsoft Jet database engine could not find the object 'newStart$'. Make sure the object exists and that you spell its name and the path name correctly.".
Msg 7350, Level 16, State 2, Line 1 Cannot get the column information from OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "(null)".
and when I ran the ACE.OLEDB I get this one:
OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "The Microsoft Office Access database engine could not find the object 'newStart$'. Make sure the object exists and that you spell its name and the path name correctly.".
Msg 7350, Level 16, State 2, Line 1
Cannot get the column information from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
I give my sql account full control permission as well.
plus I run these two as well:
USE [master]
GO
EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'AllowInProcess' , 1
GO
EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'DynamicParameters' , 1
GO
2:
sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
I would appreciate it if anyone could point me into the right direction.

strSqlQry = "Place SQL Qry Here"
vFilePath = "Database Path"
'Create Objects
Set conn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
'Open Connection
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & vFilePath & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes;"";"
'Execute Qry
rs.Open strSqlQry, conn, adOpenStatic, adLockOptimistic
'Place recorset into excel worksheet
ActiveSheet.Range("A1").CopyFromRecordset (NewRS)
rs.Close
Set rs = Nothing
Set conn = Nothing

You can use way written in this topic How do you transfer or export SQL Server 2005 data to Excel
In excel using External data menu connect to database

Related

Running a SQL Server stored proecdure with OPENROWSET in VB.Net

I am trying to automatically import tables from an excel sheet into a table in an SQL database via VB.net. So far I have done the following:
I created a stored procedure in the database which imports the table via openrowset:
CREATE PROCEDURE ImportTable
AS
SET NOCOUNT ON;
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
SELECT *
INTO [Table]
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0; Database=C:\ExcelFile.xlsm', Table$);
GO
Once created this procedure works perfectly when executed in SSMS.
I then wrote a script in VB.net to run the stored procedure with the same login details:
Dim ConnectionString As String
Dim sqlCon As SqlConnection
' Open a database connection and use it to run the stored procedure
ConnectionString = "Data Source=ServerName;" &
"Initial Catalog=DBName;" &
"User=UserName;" &
"Password=Password;" &
"Integrated Security=SSPI;"
sqlCon = New SqlConnection(ConnectionString)
Using (sqlCon)
Dim sqlComm As New SqlCommand
sqlComm.Connection = sqlCon
sqlComm.CommandText = "ImportTable"
sqlComm.CommandType = CommandType.StoredProcedure
sqlCon.Open()
sqlComm.ExecuteNonQuery()
End Using
However when I try to run the SP in VB.net (or VB excel) I get the following error:
System.Data.SqlClient.SqlException: 'Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "Unspecified error".'
I have looked around and found multiple threads on getting this to work in SSMS, but no solutions for a situation where it runs fine in SSMS but not in VB.net.
Any idea why the SP wont run through a method external to SSMS?
Craig
First Make sure the Excel file isn't open.
Then you need to check whether you have installed the 2007 Office System Driver: Data Connectivity Components which is necessary for Microsoft OLEDB ACE 12.0 driver to work.
or you can
USE [master]
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO
Nice Link

Import Excel Named Range into SQL Database

I have an excel file 'test.xlsx' which contains a sheet called 'SheetName', which contains a named range called 'NamedRange'.
I want to write a script in visual basic to import these named ranges into an SQL database. So far I have tried openrowset, but I cannot find the correct syntax to reference a named range. An example of a query that doesn't work:
USE [Test_DataBase]
GO
SELECT * INTO New
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0; Database=D:\Test.xlsx', NamedRange);
GO
The error from this is: The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" does not contain the table "NamedRange". The table either does not exist or the current user does not have permissions on that table.
I can however import the complete worksheet by using:
USE [Test_DataBase]
GO
SELECT * INTO New
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0; Database=D:\Test.xlsx', SheetName$);
GO
I have also tried:
USE [Test_DataBase]
GO
SELECT * INTO New
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0; Database=D:\Test.xlsx', SheetName$NamedRange);
GO
But that produces the following error: The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" does not contain the table "SheetName$NamedRange". The table either does not exist or the current user does not have permissions on that table.
So, can openrowset actually be used to reference named ranges? If not is there an alternative method I could use instead?
*This is my first question, I hope I've been clear enough and haven't broken any rules!
Craig
You can use SSIS.
You can use Wizard "import data": Right click DB -> Tasks -> Import Data
First install the driver, from the link below.
https://www.microsoft.com/en-us/download/details.aspx?id=13255
sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
USE YourDatabase;
GO
SELECT * INTO Table1
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0; Database=C:\your_path\test.xlsx', [Sheet1$nr]);
GO
-- 'nr' is your named range
See these links for more details.
http://www.ashishblog.com/importexport-excel-xlsx-or-xls-file-into-sql-server/
https://www.red-gate.com/simple-talk/sql/t-sql-programming/questions-about-using-tsql-to-import-excel-data-you-were-too-shy-to-ask/#sixth
https://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm
dbWb = ThisWorkbook.FullName
dsh = "SheetName$"
xlrow = Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row
SELECT * FROM [Excel 12.0;HDR=YES;DATABASE=" & dbWb & "].[" & dsh & "A1:X" & xlrow & "] as aa"

Unable to connect to DB from VBA but able to connect from Access

I'm able to connect to a database using Access, but not from VBA. In Access, I use the server name, Windows NT Integrated Security,and the database name. In VBA, I've tried many variations of variable names and values in the connection string, and the db.Open command always fails. I generally get an error about not being able to find an installable ISAM, or Multiple-step OLE DB operation generated errors. Is there a way to determine what I can use as a connection string from the working Access connection? One example of code that fails with the latter error:
Dim db As Object
Dim adoRS As Object
Set db = CreateObject("ADODB.Connection")
Set adoRS = CreateObject("ADODB.recordset")
db.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Server=sql03;" & _
"Database=db1;" & _
"Integrated Security=SSPI;"
The provider you as using in the connection string is for MS Access.
If thats the correct database then do the following.
Add the refrence "Microsoft Office 14.0 Access Database Engine object library.
Dim cnString, query As String
Dim rs As New ADODB.Recordset
'If older version of MS access then try Provider=Microsoft.Jet.OLEDB.4.0;'
cnSTring= "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<Path>;Jet OLEDB:Database Password=<Pass>;"
query = "SELECT * FROM TABLE"
rs.Open query, cnString, adOpenStatic, adLockOptimistic

Database connection error with MSSQL 2005

I've got the following code and I'm trying to establish a connection to a data base. I have MSSQL 2005 as the database and trying to connect though ODBC connection.
Importantly I'm trying to use 'Windows authentication' instead of 'SQL authentication' to login to the database. (Note that SQL auth is NOT an option for me!)
<%
Dim Conn
Set Conn = CreateObject("ADODB.Connection")
Dim ConnectionString
Conn.ConnectionString = "Server= CLMSAWN002; Database= mohan_db; Integrated Security=True;"
Conn.Open ConnectionString
Conn.CommandTimeout=120
Sub CloseConn
Conn.Close
Set Conn = Nothing
End Sub
%>
In the live environment I get the following error.
Microsoft OLE DB Service Components error '80040e21'
Multiple-step OLE DB operation generated errors. Check each OLE DB
status value, if available. No work was done.
/CustomerMarketing/_db.asp, line 10
Can you help me understand what cause this and a possible solution?

Microsoft.ACE.OLEDB.12.0 Cannot execute the query

I have this sql code. It updates a specific cell in an excel file.
SET #cmd = 'UPDATE OPENROWSET(''Microsoft.ACE.OLEDB.12.0'',''Excel 12.0;Database=C:/sompath/file.xls;HDR=NO;IMEX=0;'',''SELECT F1,F2,F3,F4,F5,F6,F7,F8,F9 FROM [Sheet1$]'')
set [F1] = ''Hello World''
where [F1] = ''<field1>'''
EXEC(#cmd)
This piece of code executes successfully in 32bit but fails in 64bit server (MSSQL Server 2012). I get this error in 64bit:
OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "No value given for one or more required parameters.".
Msg 7320, Level 16, State 2, Line 1
Cannot execute the query "SELECT F1,F2,F3,F4,F5,F6,F7,F8,F9 FROM [Sheet1$]" against OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
The file.xls is an excel file created in a 32bit pc.
Can someone help me with this issue. I've been searching around the net but really did not get the solution or even some guide to resolving it. If this question has already been posted and answered, just kindly post the exact link please.
By the way, I have already installed the ACE provider and all those settings needed.
In fact, this code works fine but not with the UPDATE statment:
DECLARE #cmd VARCHAR(1000)
set #cmd = 'SELECT * FROM
OPENROWSET(''Microsoft.Ace.OLEDB.12.0'',
''Excel 12.0;Database=C:/sompath/file.xls;HDR=NO;IMEX=0'',[Sheet1$])'
EXEC(#cmd)
Thanks!
The excel file must be created/resaved from a 64bit MS Office. That's all!