My question is regarding sql server bcp utility:
How do I export data from sql server into excel sheet with the following extensions e.g. xls,xlsx, and xlsb using bcp tool, because I can export to .csv file and .txt file extensions but with excel it can not be open after exporting with bcp.
Any worker around to export into excel sheet will do help alot.
Thanks for your help in advance
First of all there BCP don't support xls or xlsx formats.
BCP only support xml,txt and csv;
If you have to import data from excel you have .net or java or Php to create a data table with the same excel. Then use that datatable to create corresponding table in Sql
if you are using sql and C# then this might help you
string con =
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\test.xls;" +
#"Extended Properties='Excel 8.0;HDR=Yes;'";
using(OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
using(OleDbDataReader dr = command.ExecuteReader())
{
while(dr.Read())
{
var row1Col0 = dr[0];
Console.WriteLine(row1Col0);
}
}
}
or
private void GetExcel()
{
string fullPathToExcel = "<Path to Excel file>"; //ie C:\Temp\YourExcel.xls
string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=yes'", fullPathToExcel);
DataTable dt = Function_Library.DatabaseFunctions.GetDataTable("SELECT * from [SheetName$]", connString);
}
Related
I would like to output sql output to an excel file, and a sheet that I give a name to, i.e. not "Sheet1". How do I even begin code this?
Below is current code that reads sql output
$sql_output = #()
while ($rdr.read()){
$sql_output += [PSCustomObject][Ordered]#{
Col1=$rdr.GetValue(0)
Col2=$rdr.GetValue(1)
Col3=$rdr.GetValue(2)
Col4=$rdr.GetValue(3)
Col5=$rdr.GetValue(4)
}
$count=$count + 1
}
Then exports to csv
$sql_output | Export-CSV "D:\Script\Network_Threat_Protection.csv" -NoTypeInfo -Append
I would eventually like this powershell script to read multiple sql queries and output it to different sheets within excel, but let me get the jist of exporting to excel first ....
Export-CSV does not generate an Excel file. It generates a comma delimited text file that usually is set to open with Excel. Being a CSV file there is no knowledge of multiple sheets or dataset properties like sheetnames, for that you will need to use the Excel comobject (and all of its nuances).
Here is a basic example of writing a real Excel file:
$a = New-Object -com Excel.Application
$a.Visible = $True
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Cells.Item(1,1) = "A value in cell A1."
$b.SaveAs("C:\Scripts\Test.xls")
$a.Quit()
What you are trying to do is not new. There are a lot of scripts on the internet for this task. Microsoft's Script Center is a good place to find powershell scripts. Here is one that seems to do what you want.
you can use CPPLUS library for exporting tables to excel sheets..
private DataTable GetData(string tableName)
{
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
SqlCommand sqlCommand = new SqlCommand("SELECT * FROM " + tableName, sqlCon);
sqlCon.Open();
var reader = sqlCommand.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
return dt;
}
}
private void SaveExcel(DataTable dataTable, string newFile)
{
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(newFile);
ws.Cells["A1"].LoadFromDataTable(dataTable, true);
pck.SaveAs( new System.IO.FileInfo("d:\\Export\\" + newFile + ".xlsx"));
}
}
Download Source
I have used a variety of methods to try and import this data (a 97-2000 xls file generated by a crystal report server each morning that fills the first sheet fully and more than half fills the second sheet - about 120,000 records in total although it varies). There are about fourteen columns in the data, but the problem is that the first and second row have some title data taking up two columns that cannot be stopped from being entered by the report server. When I go to import the data with code such as:
Imports System.Data.OleDb
Public Class ImportData
Private Const databaselocation As String = "G:\db.mdb"
Private Const excelfileloc As String = "D:\"
Private connstr As String = "Provider=Microsoft.JET.OLEDB.4.0; Data Source=" & databaselocation & "; User Id=admin; Password=;"
Private excelstring1 As String = "Provider=Microsoft.JET.OLEDB.4.0; Data Source=" & excelfileloc
Private excelstring2 As String = "; Extended Properties=""Excel 8.0; HDR=NO; IMEX=1"";"
Public Function ImportExcel() As Boolean
Dim connection As OleDb.OleDbConnection = New OleDb.OleDbConnection(connstr)
Dim command As New OleDb.OleDbCommand
connection.Open()
command.Connection = connection
Try
Using conn As New OleDbConnection(excelstring1 & "excel.xls" & excelstring2)
Using cmd As New OleDbCommand()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO [MS Access;Database=" & databaselocation & "].[dbo_impExcel] SELECT * FROM [Sheet1$]"
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
End Try
End Function
End Class
It only imports the first two lines and ignores the rest. When I then repeat the code but using [Sheet2$], the data is returned fine. If I manually go into the excel file and delete the title, the data is imported fine. At the moment I am using code to delete the title lines first, but I'm sure there should be a better way.
In my experimentations I have even tried creating a stored procedure in an MS SQL database using OPENROWSET and the problem still occurs (although due to various job constraints this job must only rely on JET.
You might try using VB in an Excel worksheet to create and copy proper data to a new xls file. Personally I tend to save things as tab delimit or Pipe text file instead of importing as xls. Saves me the frustration of trying to Import xls.
If the file has the same title every day or based on date you should be able to just code it in a xls file which does all the work for you then closes afterward.
I have a plain text file that contains one column of numbers, and in a web client take the numbers and transfer them into a SQL Database. After retrieving the file, I store the contents in a temporary DataTable, then using SqlBulkCopy, attempt to transfer the DataTable to the database. However, once I run the web client and import the file, the program hangs. The code is listed below for what I've done so far.
Transferring Files to DataTable
private DataTable readTextFile()
{
DataTable dt = new DataTable();
FileUpload file = new FileUpload();
dt.Columns.Add("Claim Number", typeof(Int32));
file = (FileUpload)grdCriteria.FindControl("exportUpload");
StreamReader read = new StreamReader(file.PostedFile.FileName);
while ((read.ReadLine()) != null)
dt.Rows.Add((Int32.Parse(read.ReadLine())));
return dt;
}
Insert DataTable into SQL Database
DataTable dt = readTextFile();
SqlBulkCopy bk = new SqlBulkCopy(Profile.ConnectionKey.CAM);
bk.DestinationTableName = dt.TableName;
bk.WriteToServer(dt);
Thanks!
I have win application and i get this error when i want to connect the database to my app
error:
An attempt to attach an auto-named database for file C:\Users\Aren\Desktop\DB\REGISTRATION.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
public class DALBase
{
protected SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\\Users\\Aren\\Desktop\\DB\\REGISTRATION.mdf;integrated Security=true ; User Instance=True");
protected SqlCommand com = new SqlCommand();
protected SqlDataAdapter da = new SqlDataAdapter();
protected DataSet ds = new DataSet();
}
public DataSet GetStudent(string filter)
{
DataSet dset = new DataSet();
using (SqlCommand cmd = new SqlCommand())
{
string cmdstring = string.Format("Select * from {0}"
, Common.Data.Student.Table_Name);
if (!string.IsNullOrEmpty(filter)) cmdstring += " where " + filter;
cmd.CommandText = cmdstring;
cmd.Connection = this.con;
cmd.Connection.Open();
cmd.CommandText = cmdstring;
cmd.Connection = this.con;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dset, Common.Data.Student.Table_Name);
return dset;
}
}
NOTE: ALSO i got 3 project in my solution the DALBASE and GETSTUDENT methods are in one project and i call them from other project to get the data for me.
I believe i have encountered this problem in the past. in my situation I loaded an application in visual Studio which when run would load a database and attach to SQL Server. Somehow when I closed the application it didn't deattach the database from SQL SERVER and next time I ran the app it complained with a similar if not the same message.
If you have SSMS installed open up to the .\SQLEXPRESS instance and see if you have a Registration*.mdf file attached. Or if you don't have SSMS open up your command line and type...
sqlcmd -S .\SQLEXPRESS -Q "select name from sys.databases"
This will show you all your databases attached/online on that instance.
Hope this helps.
Please tell me how to save and show Richtextbox's data in database and retrive it in saved format and which datatype should be used to save that data. i am using vb.net and MY SQL
if your data contains image/icons or some special symbols then its better to go for BLOB otherwise you can go with varchar datatype.
You can use the BLOB datatype.
Your RTF Data feild should be "Memo".
private void InsertToMemo()
{
using (OleDbConnection oleDbConn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\AD.mdb"))
{
OleDbCommand oleDbCmd = new OleDbCommand("insert into Table2 values(1,'" + this.richTextBox1.Rtf + "')", oleDbConn);
oleDbCmd.Connection.Open();
oleDbCmd.ExecuteNonQuery();
}
}
private void ReadFormMemo()
{
using (OleDbConnection oleDbConn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\AD.mdb"))
{
OleDbCommand oleDbCmd = new OleDbCommand("select Field1 from Table2", oleDbConn);
oleDbCmd.Connection.Open();
OleDbDataReader oleDbDataReader = oleDbCmd.ExecuteReader();
oleDbDataReader.Read();
this.richTextBox2.Rtf = oleDbDataReader.GetString(0);
}
}