The company that I work in has a new project. two of the employees will visit each store to record some information. The project is simple, We just want to insert that data, which has been collected by the two employee, to a sql database.
Unfortunately, the two employees will just have a laptop, which is offline. So, I can't use a synchronization technique to insert the data.
My solution is to allow the two employee to write the data in an excel sheet and then I try to find a way to insert that excel sheet into the sql database.
My question
is it possible to insert the excel sheet into the sql database?
is there any better solutions please?
Note
The database is very very simple, it is just a one table with three columns. ID, StoreName, and StoreProductsNumber
Or you can schedule query like this to run on server and auto sync:
INSERT INTO database..table(ID,StoreName,StoreProductsNumber)
SELECT
1 AS ID,
LTRIM(RTRIM([StoreName])),
LTRIM(RTRIM([StoreProductsNumber])),
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=C:\folder\excelfile.xls','select * from [sheet1$]')
Try This
public string GetDataTableOfExcel(string file_path)
{
using (OleDbConnection conn = new OleDbConnection())
{
DataTable dt = new DataTable();
string Import_FileName = Server.MapPath(file_path);
//Import_FileName = System.IO.Path.GetDirectoryName(file_path);
string fileExtension = Path.GetExtension(Import_FileName);
if (fileExtension == ".xlsx")
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'";
using (OleDbCommand comm = new OleDbCommand())
{
comm.CommandText = "Select * from [Sheet1$]";
comm.Connection = conn;
using (OleDbDataAdapter da = new OleDbDataAdapter())
{
da.SelectCommand = comm;
da.Fill(dt);
}
}
}
}
Now Your Data in DataTable. You can create insert query from datatable's data.
file_path is excel file's full path with directory name.
Through import functionality of SQL server u can achieve it...
http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/
This can be achieved using Import/Export tool. I will try and add a few stwps that can help you through the process.
Using SSMS, In the Object Explorer pane, right click on the database > Tasks > Import
Select Data Source as Microsoft Excel and Click on Browse to search and select your excel file. Fill the appropriate fields and click next
Destination will be populated as you invoked the tool from the target DB. Click Next
Select copy data from one or more tables or vies radio button and click next
Now select the Excel Tab that contains the required data and under the source and select the target table from the Destination column. Click on Edit mapping and verify if the columns are mapped to the correct destination tables. Click Next
Click finish to run the package and load data into SQL Server
You could also be interested in viewing this video that talks about the exact same thing.
http://www.youtube.com/watch?v=GG2N2iI0W3M
Hope this helps.
Related
I am using the below code to import a CSV file to my Access DB. I just have a couple of questions.
Con.Open()
Dim strSqlCommand = "SELECT F1 AS id, F2 AS firstname " &
"INTO MyNewTable " &
"FROM [Text;FMT=Delimited;HDR=No;CharacterSet=850;DATABASE=" & GlobalVariables.strDefaultDownloadPath & "].Airports.csv;"
Dim sqlCommand = New System.Data.OleDb.OleDbCommand(strSqlCommand, Con)
sqlCommand.ExecuteNonQuery()
Con.Close()
How can I change the Character Set to UTF-8? If I enter utf8 instead of 850 I get an error.
Also, the first line of my CSV file contains the column names. Can I amend the above code to take that in to account?
Regards,
Andrew
You could run into trouble trying to import and select all at once, for one thing you may not want to leave converting data types up to Access. For that, you will need 2 connections and SQL string to select from one another to insert into the other.
The connection string will need to look something like this:
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\Tmp;Extended Properties='TEXT;HDR=Yes;FMT=Delimited;CharacterSet=ANSI'"
Note that just the path is listed and the Extended Properties are enclosed in ticks. If the first line has headers/field names then HDR=Yes will skip them in the result set. One of the benefits of having field names as the first line is that OleDB will use them as column names (no need for F1 As foo, F2 As bar; in fact that will fail because they have been renamed from F1, F2...).
The SQL to read from the CSV:
"SELECT * FROM filename.csv"
There are several ways to process it. You could use a reader to read a row at a time to INSERT them into the Access database. This is probably simpler: get all the data from the CSV into a DataTable and use it to INSERT into Access:
Private myDT As DataTable ' form level variable
...
Dim csvStr As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Temp\Tmp;Extended Properties='TEXT;HDR=Yes;FMT=Delimited;CharacterSet=ANSI'"
Dim csvSQL = "SELECT * FROM Capitals.csv" ' use YOUR file name
Using csvCn = New OleDbConnection(csvStr),
cmd As New OleDbCommand(csvSQL, csvCn)
Using da As New OleDbDataAdapter(cmd)
myDT = New DataTable
da.Fill(myDT)
End Using
End Using
For Each r As DataRow In myDT.Rows
'ToDo: INSERT INTO Access
Next
The Connection, Command and DataAdapter are all resources, so they are in USING blocks to dispose of them when we are done with them. myDT will have a collection of Rows, each with a collection of Items representing the fields from the CSV. Just loop thru the rows adding the desired items to the Access DB.
You will very likely have to do same data type conversion from String to Integer or DateTime etc.
As for the question about UTF8 - you can use the Codepage identifier. If you leave it off the connection string it will use whatever is in the Registry which may also work. For UTF8 use CharacterSet=65001.
I am doing a programming project for my visual basic class, we are using Visual Studios 2012. What I would like to know, if at all possible is if there is a way to export an Access table into an Excel file (by pressing a menu item in the form) that I can then put the name of the file as the time and date the file was created.
Right now, I have one form, with a menu-strip, where I placed the option to export to Excel.
The program has the user enter items that they are sending to and receiving from a laundry with quantities. I have got the moving of data from the form to the Access table finished, but I need to be able to create an excel file with that data from that table in it with the day and time as the file name. I am not using VBA, and I think it may be too late to start using VBA at this stage in the project. I am using the techniques from a series of videos I found on YouTube, here is the link:
https://www.youtube.com/watch?v=07ioTflBrHQ
I am completely stuck on this, and all the solutions I look for are in VBA, but I need whatever Visual Studios 2012 is using. Any help offered will greatly appreciated, and if VBA is required, I would ask that you would treat me as a beginner with any explanations or code you may have, because I am a beginner to visual basic, and I have no idea how VBA works.
Edit:
The technique described here looks promising, but one of the fields I want to export is a Calculated field and it triggers the error
Calculated columns are not allowed in SELECT INTO statements.
Perhaps there is a workaround for this?
It seems that Access does not allow Calculated Fields to be included in SELECT INTO statements. For a table named [SampleData]
SampleID Prefix FirstName LastName FullName
-------- ------ --------- -------- ----------------
1 Mr Gord Thompson Mr Gord Thompson
2 Miss Anne Elk Miss Anne Elk
where [FullName] is a Calculated Field, if we try
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText =
#"SELECT SampleID, FullName " +
#"INTO [Excel 8.0;HDR=YES;DATABASE=C:\__tmp\zzzNew.xls].[Sheet1] " +
#"FROM SampleData";
cmd.ExecuteNonQuery();
}
we get the error
Calculated columns are not allowed in SELECT INTO statements.
However, we can fool Access into doing our bidding by using the calculated field in an expression for one of the output columns:
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText =
#"SELECT SampleID, '' & FullName AS FullName " +
#"INTO [Excel 8.0;HDR=YES;DATABASE=C:\__tmp\zzzNew.xls].[Sheet1] " +
#"FROM SampleData";
cmd.ExecuteNonQuery();
}
(This is C# code, but the VB.NET code would be very similar.)
Edit re: comment
To create an Excel document in the newer .xlsx format, use this
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText =
#"SELECT SampleID, '' & FullName AS FullName " +
#"INTO [Excel 12.0 Xml;HDR=YES;DATABASE=C:\__tmp\zzzNew.xlsx].[Sheet1] " +
#"FROM SampleData";
cmd.ExecuteNonQuery();
}
I'm trying to connect to to a foxpro table (.dbf) from a test vb.net form.
I recieve an OleDbException with the message "Cannot open file c:\emp\emptbl.dbf"
Have tried with both of the following connection strings:
Provider=VFPOLEDB.1;Data Source=C:\emp\emptbl.dbf
from the MSDN article here
Provider=vfpoledb;Data Source=C:\emp\emptbl.dbf;Collating Sequence=machine;
from connectionstrings.com
The latter seems to be the type to use when connecting to a single table, but the same exception is thrown regadless of which is used.
I can open and perform the same query okay in visual foxpro 6.0.
Here's my code:
Dim tbl As DataTable = New DataTable()
Using con = New OleDbConnection(conString)
cmd = New OleDbCommand() With {.Connection = con, .CommandType = CommandType.Text}
Dim sSQL As String = "SELECT * FROM(EMPTBL)"
cmd.CommandText = sSQL
Dim adp As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim ds As DataSet = New DataSet()
con.Open()
adp.Fill(ds)
con.Close()
If (ds.Tables.Count > 0) Then
tbl = ds.Tables(0)
End If
End Using
Return tbl
The OleDB provider should only connect to the PATH where the tables are... not the actual file name. Once you connect to the PATH, you can query from ANY .Dbf file that is located in it
Provider=VFPOLEDB.1;Data Source=C:\emp
select * from emptbl where ...
You can also look at other connection string settings at
ConnectionStrings.com
UPDATE per comment.
It appears you are getting closer. with your attempt without the () parens. In VFP, within parens, it interprets that as "look for a variable called EMPTBL", and from its value is the name of the table to query from. Not something you would need to apply via OleDB connection.
Now, cant open the file is another. Is it POSSIBLE that another application has the table open and the file is in exclusive use? and thus can not be opened by the .net app too? Even for grins, if you open VFP, and just do a simple create table in the C:\Emp folder and put a single record in it, then you know no other program will be using it as it is a new file. Quit out of VFP and try to query THAT table. There should be no locks, no other program is expecting it, so it should never be opened by anything else and you should be good to go.
I'm a bit puzzled here. I did a form containing a simple datagridview containing data from an MDB file. The connection was alltogether done by Visual Studios wizard so alot of stuff was created automatically. Then I databinded the textboxes to each column in the database and managed to update the database via my own command buttons such as "Update" with this code:
Me.MainTableBindingSource.EndEdit()
Me.MainTableTableAdapter.Update(Me.DBDataSet.MainTable)
Me.DBDataSet.MainTable.AcceptChanges()
This doesn't seem to work with sql. At this point, I've done everything from scratch in this order, added a datagridview and added a database connection with the wizard when connecting the datagridview to a database. Only this time around I created an SQL connection instead.
And Visual Studio created "MainTableTableAdapter", "DBDataSet", "DBDataSet.MainTable".
The SQL server is something which was installed automatically when installing Visual Studio and it does seem to work after creating the table adapter and dataset if there's data in it. In some time I plan to use an SQL Server on the internet which hosts the dataset. So I want to be able to easily edit the source.
The only thing missing now is how to add a row, delete selected row and editing selected row via my own textboxes. More like a fill-in form. Any ideas to put me in the right direction? I've tried googling it and I've found some stuff, but most of it contains stuff on how to create the datasets and etc. And I'm not sure what Visual Studio has done automatically. And I want to update everything just as easily as I did with these three lines of code when I used a local MDB file.
If it's SQL you can do something like this. Here's an example delete function:
Public Shared Function DeleteStuff(ByVal id As Integer) As Integer
Dim query As String = _
"DELETE FROM tbl_Stuff " & _
"WHERE ID_Stuff = " & id & ";"
Dim connection As SqlConnection = YourDB.GetConnection
Dim deleteCommand As New SqlCommand(query, connection)
Dim rowCount As Integer = 0
Try
connection.Open()
rowCount = deleteCommand.ExecuteNonQuery()
Catch ex As SqlException
Throw ex
Finally
connection.Close()
End Try
Return rowCount
End Function
There may be better ways, but you can always pass in SQL queries.
EDIT: Sorry this is more than three lines of code. ;)
I need to open foxpro free tables in vb.net using the oledb connection.
But... I only need to get the column names. I don't really need to 'select' anything.
I am trying to dynamically browse through all our free tables and set up a listing of every column from every file and xref that to another free table that contains a description of each column.
I have a working model now, but it requires that I do...
SELECT TOP 1 FROM "File" ORDER BY 1
But on the largest table, it takes over two minutes just to read in the first record and there are over 250 tables. Overall, it takes between 15 and 20 minutes.
Or, is there another way to only get the first record of the table without using 'ORDER BY'?
Here's what I have so far. "File" is passed in as a parameter.
It would contain info like "C:\data\table1.dbf"
Dim filePath As String
filePath = IO.Path.GetDirectoryName(file)
myOledbConnection = New OleDbConnection("Provider=VFPOLEDB.1;Data Source=" & filePath & ";Collating Sequence=MACHINE")
myOledbCommand = New OleDbCommand
myOledbDataAdapter = New OleDbDataAdapter
Dim fields, from, order As String
fields = "select top 1 *"
from = " from " & file
order = " order by 1"
myOledbCommand.CommandText = fields & from & order
myOledbCommand.Connection = myOledbConnection
myOledbDataAdapter.SelectCommand = myOledbCommand
myOledbDataAdapter.Fill(dt)
I then take the datatable (dt) and loop through to get the column information.
I would like it to be as quick as Visual Studio is when I create a dataset and load all tables from the directory through the wizard. It is able to very quickly find all the column information without reading in the data from the table.
Let me know if you need more information.
Thanks.
Why do you need to get any records at all? You should be able to say:
SELECT * FROM "File" where 1 = 0
This will give you an empty result set, will also give you metadata on the projection returned.
You might also want to look into the GetOleDbSchemaTable method on the OleDbConnection class, as it will allow you to get information about the schema of the database without having to perform a query.
You can also use the Microsoft ADO Extensions for Data Definition Language and Security through COM interop (mxADOX.dll) to get the schema information as well.
I have not tried this/. But, it looks like the way to go.
Specifically the "GetSchema" method on OleDbConnection instance.
http://msdn.microsoft.com/en-us/library/ms254934(VS.80).aspx