Click here to Skip to main content
15,887,939 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to export data from database to Excel file. This is my code when I use MS Access:
VB.NET
Dim My_Connection As New System.Data.OleDb.OleDbConnection
Dim sql As String
Dim cmd As System.Data.OleDb.OleDbCommand
    
My_Connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myDB.mdb;Persist Security Info=False;Jet OLEDB:Database Password=myPassword"
My_Connection.Open()

sql = "SELECT product_ID, client_ID INTO [Excel 12.0;DATABASE=E:\test.xls].[EXPORT] FROM Orders"
cmd = New System.Data.OleDb.OleDbCommand(sql, My_Connection)
cmd.ExecuteNonQuery()


This code work perfectly. I don't have Excel in my PC. I created xls file that I open on another computer with Excel or Apache Calc.
But I move database to SQL Server 2014.

What I have tried:

I change my code:

VB.NET
Dim My_Connection As New System.Data.SqlClient.SqlConnection
Dim sql As String
Dim cmd As System.Data.SqlClient.SqlCommand

My_Connection.ConnectionString = "Data source=localhost;Initial Catalog=myDB;Integrated Security=false;uid=sa;password=myPassword;"
My_Connection.Open()

sql = "SELECT product_ID, client_ID INTO [Excel 12.0;DATABASE=E:\test.xls].[EXPORT] FROM Products"
cmd = New System.Data.SqlClient.SqlCommand(sql, My_Connection)
cmd.ExecuteNonQuery()

When I try to run I just get the error message:
The specified schema name "Excel 12.0;DATABASE=E:\test.xls" either does not exist or you do not have permission to use it.
Posted
Updated 12-May-17 9:52am
v2
Comments
Richard MacCutchan 12-May-17 3:30am    
The error message is quite clear. Make sure the file exists at that path, and that it is writable by your application.

1 solution

Start here: Excel connection strings - ConnectionStrings.com[^]
There you'll find an examples of connection-string and command text. For example:
Quote:
SQL syntax "SELECT [Column Name One], [Column Name Two] FROM [Sheet One$]". I.e. excel worksheet name followed by a "$" and wrapped in "[" "]" brackets.


A proper connection string is:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;
Extended Properties="Excel 12.0;HDR=YES";


A command-text to insert data into Excel is:
SQL
INSERT INTO [EXPORT$]
SELECT product_ID, client_ID
FROM Products;


For further details, please see:
INSERT INTO Statement (Microsoft Access SQL) [Access 2007 Developer Reference][^]
How to: Insert, Update, and Delete Records From a Table Using Access SQL [Access 2007 Developer Reference][^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900