Export into excel file without headers c# using Oledb - c#

I'm using OleDB and I want to export my objects into excel table. Each row in the sheet will be one of my objects. The problem is that I don't know how to insert data when there's no column headers in the sheet.
This one:
commandString = "Insert into [Sheet1$] values('test1', 'test2')"
throws this exception:
Number of query values and destination fields are not the same.
My connection string is:
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+filename+";Extended Properties='Excel 8.0;HDR=No'"

If the connection string contains HDR=NO then the Jet OLE DB provider automatically names the fields for you (F1 for the first field, F2 for the second field, and so on).
I will try to change your query in this way
commandString = "Insert into [Sheet1$] (F1, F2) values('test1', 'test2')"
this works only after you have created the excel file and have something inserted in the first two cells of the first row in Sheet1

You need to specify which values you are writing, since you don't use an HDR - just use the cells.
The Error "number of query values" simplies implies that - there are no fields assigned to the values supplied.
Update: #Steve was right with the Fields (F1,F2,etc), and the code below does work here:
OleDbConnection Cn = new OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=No\"", #"D:\test.xls"));
Cn.Open();
OleDbCommand Com = new OleDbCommand("INSERT INTO [Sheet1$](F1,F2) VALUES('test3','test4');", Cn);
Com.ExecuteNonQuery();
Cn.Close();

Related

Transferring Excel data into SQL table with different columns

I want user to transfer data from Excel files into SQL using a C# WinForms application one file at a time. The Excel files consist of similar columns, and so there might be some new columns or columns absent. Row data will vary.
For example:
Excel file 1: Name, City State
Excel file 2: Name, City, Zip
Excel file 3: Name, City, County
In my existing SQL table I have columns: Name, City, Population, Schools
How do I insert the new Excel files with similar column names into an existing SQL database?
My thought so far is to copy the new Excel file data into temporary tables, and then insert that into the existing SQL table. The problem is, I don't know how to write C# code (or a SQL query) that would insert new Excel data with more or less columns than the existing SQL table.
You need No-SQL for this purpose, if you need to enter columns that are not already part of the table then sql is not a good option if you use c# to alter table then be careful to the consequences. If you are sure about all possible column names in front then try altering your table before you start insert
This should't be too hard. Export your data from Excel to a staging table table in SQL Server. The C# code may look something like this.
public void importdatafromexcel(string excelfilepath)
{
//declare variables - edit these based on your particular situation
string ssqltable = "tdatamigrationtable";
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have
different
string myexceldataquery = "select student,rollno,course from [sheet1$]";
try
{
//create our connection strings
string sexcelconnectionstring = #"provider=microsoft.jet.oledb.4.0;data source=" + excelfilepath +
";extended properties=" + "\"excel 8.0;hdr=yes;\"";
string ssqlconnectionstring = "server=mydatabaseservername;user
id=dbuserid;password=dbuserpassword;database=databasename;connection reset=false";
//execute a query to erase any previous data from our destination table
string sclearsql = "delete from " + ssqltable;
sqlconnection sqlconn = new sqlconnection(ssqlconnectionstring);
sqlcommand sqlcmd = new sqlcommand(sclearsql, sqlconn);
sqlconn.open();
sqlcmd.executenonquery();
sqlconn.close();
//series of commands to bulk copy data from the excel file into our sql table
oledbconnection oledbconn = new oledbconnection(sexcelconnectionstring);
oledbcommand oledbcmd = new oledbcommand(myexceldataquery, oledbconn);
oledbconn.open();
oledbdatareader dr = oledbcmd.executereader();
sqlbulkcopy bulkcopy = new sqlbulkcopy(ssqlconnectionstring);
bulkcopy.destinationtablename = ssqltable;
while (dr.read())
{
bulkcopy.writetoserver(dr);
}
oledbconn.close();
}
catch (exception ex)
{
//handle exception
}
}
Then, in SQL Server, move the data from the staging table to your final production table. Your SQL may look something like this.
insert into production
select ...
from staging
where not exists
(
select 1 from staging
where staging.key = production.key
)
That's my .02. I think you will have a lot more control over the whole process that way.
If you are reading this question then my answer to this other question may be helpful for you (just create a Class to handle each row information, process the excel file and perform a bulk insert like explained there):
Bulk insert is not working properly in Azure SQL Server
I hope it helps.

Data is missing while reading excel file using OLEDB

I am using OLEDB to read excel file into datatable. But the problem is, some values are missing(Empty). In my excel sheet one column datatype is General, it has mixed values like string and integers. Most of the cell values are integers. Why OLEDB is skipping string values.
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + "; Extended Properties=\"Excel 12.0;IMEX=1\";";
OleDbCommand myAccessCommand = new OleDbCommand();
myAccessCommand.CommandText = "Select * from [" + sheetName + "]";
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);
myDataAdapter.Fill(myDataSet);
Check following link and see points under "RESOLUTION":
http://support.microsoft.com/kb/194124
Please see point 2 NOTE.
Setting IMEX=1 is entirely dependent on your registry settings. By default, first 8 rows are checked to determine the data type. IMEX=1 can give unpredictable behaviors, such as skipping string values. There is also one small workaround for this problem. Just add single quote (') before every cell value in excel. Every cell will be treated as string.
Add IMEX=1 to the connection string as below:
string con = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};" + #"Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'", fileName);

excel data to datagridview through dataset using OLE skips the initial blank rows and blank columns

I am using OLE related API's for reading data to DataSet and later to view in DataGridView. The source is an excel file. If the first row or column is empty than that row or column is getting skipped. I wish to read the data irrespective of empty/has data. Other rows/columns even if its empty its working fine, but only starting is missing.
I read about ColumnHeader and tried changing connectionString (HDR=NO) and others but nothing worked out.
Any additional things need to be specified while calling the API? One to one mapping with the excel column and the DataGridView column is missing because of skipping this initial blank rows/columns.
Anything needs to be added/modified to this OleDbDataAdapter parameter, which actually reads the data and fills to dataset:
OleDbDataAdapter cmd = new System.Data.OleDb.OleDbDataAdapter(
"select * from [" + worksheetName + "$]", con);
Yes, I am setting some required information and calling a method to read data from each sheet. I am not doing any action on the rows/columns except reading them.
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
System.Data.DataTable getWorksheetData(OleDbConnection con, OleDbDataAdapter cmd)
{
con.Open();
System.Data.DataSet excelDataSet = new DataSet();
cmd.Fill(excelDataSet);
con.Close();
return excelDataSet.Tables[0];
}
My connection string is:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileName + "; Extended Properties=\"Excel 12.0 Xml;HDR=NO;Mode=Read;ReadOnly=True;\"";

OLEDB reading CSV file returns first column only

I'm trying to read a pipe separated text file. First lines are
"BewerberID"|"Druck"|"Druckdatum"|"HistorieID"|"Bearbeiter"|"BewZuBewGruppeID"|"Bemerkung"
"12586"|"EinladungOFD.dot "|"03.02.2003 00:00:00"|"162"|"Petersen "|"20295"|"ungültig"
"12807"|"EinladungOFD.dot "|"27.02.2003 00:00:00"|"258"|"Petersen "|"20617"|""
"12807"|"EinladungOFD.dot "|"28.02.2003 00:00:00"|"270"|"Petersen "|"20617"|""
Below is the LINQpad script i'm using. It runs perfectly, but does return values from the first colum only.
string mySelectQuery = "SELECT * FROM Historie.CSV";
OleDbConnection connection = new OleDbConnection
("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\;" +
"Extended Properties=\"text;HDR=YES;IMEX=1;FMT=Delimited(|)\"");
connection.Open();
OleDbCommand cmd = connection.CreateCommand();
cmd.CommandText = mySelectQuery;
OleDbDataReader rdr = cmd.ExecuteReader();
rdr.Dump();
rdr.Close();
connection.Close();
This returns the first column only.
BewerberID
12586
12807
12807
I tried switching to column names SELECT BewerberID, Druck FROM Historie.CSV but get an error stating "At least one parameter has no value". (BTW: SELECT BewerberID FROM Historie.CSV does work and returns the same as *)
What do i have to do to get all columns back?
Create a file named schema.ini in the same folder as Historie.CSV (in this case C:\). The file should have the following contents:
[Historie.csv]
Format=Delimited(|)
ColNameHeader=True
Then try rerunning the code.
Some links:
When reading a CSV file using a DataReader and the OLEDB Jet data provider, how can I control column data types?
Schema.ini File (Text File Driver)

How do I sum all rows of a specific header in an excel file with c#?

I have a excel table with 1 sheet. That sheet has headers in row 1.
One of the headers is Amount.
I want to read all rows from that header and get the sum of it independently of the number or rows, which is never the same, into a variable of type float.
I'm doing this with c#.
I open the workbook, I get the active sheet and then nothing, I get blocked.
How do I go about this?
Rui Martins
You could use OleDB instead of Excel.Interop
string con = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\test.xls;" +
"Extended Properties='Excel 8.0;HDR=Yes;'";
using(OleDbConnection c = new OleDbConnection(con))
{
c.Open();
string selectString = "SELECT SUM(Amount) FROM [Sheet1$]";
using(OleDbCommand cmd1 = new OleDbCommand(selectString))
{
cmd1.Connection = c;
var result = cmd1.ExecuteScalar();
Console.WriteLine(result);
}
}
This example use the old Microsoft.Jet.OleDB.4.0 provider, but works equally with the new Microsoft.ACE.OLEDB.12.0
Take a look at this article, you should be able to loop through the rows and get the total by adding the cell values altogether.
MSDN article on how to retrieve excel cell values.

Categories

Resources