Insert Excel file data into database table using c# [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am developing on web application that will get the excel file using FileUpload control in asp.net c#. Now when click on submit button, i want to insert the excel data into my database table. I have database in SQL-Server. The field of database table & excel file are same.I want to insert that excel's data into my database table. So how can i do this?

Others have mentioned using Excel interop to read the Excel file in the comments, but this is NOT safe to do for a web application that may have multiple users.
To get started, have a look at the Excel Data Reader project. I've used this several times for processing Excel files from a web application and it works quite well.

You can use OLEDB classes to read directly from Excel file using the Excel drivers in OleDbConnection. Get the data in a datatable and save it to database.
string connectString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\\testit.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection conn = new OleDbConnection(connectString);
OleDbDataAdapter da = new OleDbDataAdapter("Select * From [Sheet1$]", conn);
DataTable dt = new DataTable();
da.Fill(dt);
// Save your datatable records to DB as you prefer.

I've been testing NPOI as a replacement for another 3rd party Excel parsing library.
https://code.google.com/p/npoi/
So far it seems to work pretty well and have a very complete feature set. Of course, if all you need is very basic Excel data reading (and no writing), then the other DB connection style interfaces mentioned here should work well enough.
EDIT: added sample code
using( FileStream fs = new FileStream("file.xls", FileMode.Open, FileAccess.Read) )
{
HSSFWorkbook wb = new HSSFWorkbook(fs);
double value = wb.GetSheet("Sheet1").GetRow(1).GetCell(1).NumericCellValue;
// read other values as necessary.
}

try the following code . maybe its crude but it works
string connectString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\\data\\exceltest.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection conn = new OleDbConnection(connectString);
OleDbDataAdapter da = new OleDbDataAdapter("Select * From [Sheet1$]", conn);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
SqlConnection sqlc = new SqlConnection(#"server=.\SQLEXPRESS;user id=sa;pwd=windows;database=exceltest");
sqlc.Open();
SqlCommand cmd = new SqlCommand("select * from table1", sqlc);
SqlDataAdapter sda = new SqlDataAdapter("select * from table1", sqlc);
sda.InsertCommand = new SqlCommand("insert into table1", sqlc);
DataTable dbset = new DataTable();
da.Fill(dbset);
SqlCommand cmdinsert = new SqlCommand();
cmdinsert.Connection = sqlc;
foreach (DataRow dsrc in dt.Rows)
{
string insertcommand = "insert into table1" + dbset.TableName + " ";
string cols = "";
string vals = "";
DataRow dr = dbset.NewRow();
foreach (DataColumn clm in dt.Columns)
{
dr[clm.ColumnName] = dsrc[clm.ColumnName].ToString(); ;
if (cols.Length > 0)
{
cols += ",[" + clm.ColumnName+"]";
}
else
{
cols = "["+clm.ColumnName+"]";
}
if (vals.Length > 0)
{
vals += "," + "'" + dsrc[clm.ColumnName].ToString() + "'";
}
else
{
vals = "'" + dsrc[clm.ColumnName].ToString() + "'";
}
}
insertcommand += "(" + cols + ") values("+vals+")";
cmdinsert.CommandText = insertcommand;
cmdinsert.ExecuteNonQuery();
insertcommand = "";
}
sqlc.Close();

Related

C# Retrieve data from a XLS

I have a class ParseXLS(string name, string driveLincence, string sex)
My .xls looks like :
Name | Drive Licence | Sex
A - Y - M
B - N - F
I want to read a big .xls and put all this data inside my class.
To read my .xls i used :
OleDbDataReader reader;
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
xlsFilePath + ";Extended Properties=Excel 8.0");
OleDbCommand command = new OleDbCommand("select * from [sheet1$]", con);
con.Open();
But i don't know how to obtain a List or ObservableCollection..
I found many hard solutions, lot of code, and not clear for me, i hope someone can help me with an easy solution.
Thanks in advance
You can load the data into a DataTable:
var results = new DataTable();
using(var con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ xlsFilePath + ";Extended Properties=Excel 8.0"))
{
var command = new OleDbCommand("select * from [sheet1$]", con);
con.Open();
var adapter = new OleDbDataAdapter(command);
adapter.Fill(results);
}
And from there, loop through the results and use the data however you need to:
foreach(DataRow row in results)
{
var name = row["name"].ToString();
var driversLicense = row["Drive Licence"].ToString();
var sex = row["Sex"].ToString();
//Do what you need
}
An alternative is to use a 3rd party library like EPPlus.

Update entire Excel table with OleDb

My excel simulation needs to be imported into C#, after which the table needs to be able to be refreshed. The simulation revolves around randomly generated numbers. The random numbers are the only columns that change, since I'm doing that manually. The surrounding columns should update with the random numbers. I have tried various things but no luck so far.
Also, as the code is now, the
adp.Update(excelDataSet);
command invokes the error "Update requires a valid UpdateCommand when passed DataRow collection with modified rows." The table is only loaded into the gridview at all when it is commented out.
Here is my code atm. Thanks in advance.
string fileName = #"C:\simulation.xlsx";
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;READONLY=FALSE\"";
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
con.Open();
OleDbCommand selectCommand = new OleDbCommand("select * from [SHEET1$]", con);
OleDbDataAdapter adp = new System.Data.OleDb.OleDbDataAdapter();
adp.SelectCommand = selectCommand;
DataSet excelDataSet = new DataSet();
adp.Fill(excelDataSet);
for (int i = 0; i < 29; i++)
{
excelDataSet.Tables[0].Rows[i][1] = Math.Round(r.NextDouble(), 2);
excelDataSet.Tables[0].Rows[i][6] = Math.Round(r.NextDouble(), 2);
excelDataSet.Tables[0].Rows[i][8] = Math.Round(r.NextDouble(), 2);
}
adp.Update(excelDataSet);
gridview.DataSource = excelDataSet.Tables[0];
con.Close();
Add a line that build a OleDbCommandBuilder
....
OleDbDataAdapter adp = new System.Data.OleDb.OleDbDataAdapter();
adp.SelectCommand = selectCommand;
OleDbCommandBuilder cb = new OleDbCommandBuilder(adp);
adp.UpdateCommand = cb.GetUpdateCommand();
....
This will create the UpdateCommand in the OleDbDataAdapter for you, (can be used also for the InsertCommand and DeleteCommand)

Oledb connection and query read only one column from excel spreadsheet [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can i select specific columns from excel sheet in c#?
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|2.xls;Extended Properties='Excel 8.0;HDR=no;'";
string query = "SELECT * FROM [Sheet1$]";
DataSet excelDataSet = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(query, strConn);
da.Fill(excelDataSet);
GridView1.DataSource = excelDataSet;
GridView1.DataBind();
GridView1.HeaderRow.Cells[0].Text = "CheckNumber";
I have this code to read an Excel Spreadsheet being loaded from a website and being displayed in a gridview. I would like to simply just read column A on the spreadsheet. I think I should be able to change this string query = "SELECT * FROM [Sheet1$]"; but all my efforts have been futile. Can someone point me in the right direction, or is there a better way to do this.
it looks like the way to do this is simply
string sql = "SELECT F1, F2, F3, F4, F5 FROM [sheet1$];
Thanks for the comments everyone.
I believe your problem lies in the fact that a spreadsheet is not a database. A spreadsheet is under no obligation to be rectangular or have cells of the same type. So saying you want a column ASSUMES that that column exists for all rows and is of the same type. So before you issue SQL against it you need to convert to a vector of the same type.
Here is what I use to read an Excel Spreadsheet and return it as a DataTable and if you focus in on the following section where I am able to query all of the workbooks in the Spreadsheet by looping through the dtSchema DataTable object to find the names of the different worksheets:
public static DataTable GetExcelData(string connectionString)
{
string sql = string.Empty;
using (OleDbConnection cn = new OleDbConnection(connectionString))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
using (OleDbCommand command = cn.CreateCommand())
{
cn.Open();
DataTable dtSchema = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
foreach (DataRow dr in dtSchema.Rows)
{
//Will Loop through the name of each Worksheet
Console.WriteLine(dr["Table_Name"]);
}
string firstSheetName = dtSchema.Rows[0].Field<string>("TABLE_NAME");
sql = "SELECT * FROM [" + firstSheetName + "]";
command.CommandText = sql;
adapter.SelectCommand = command;
adapter.Fill(dt);
if (dt.Rows.Count == 0)
{
OleDbDataReader reader = command.ExecuteReader();
dt.Load(reader);
}
cn.Close();
return dt;
}
}
}
}

InvalidOperationException with service_timer

I'm developing a windows service in C# and it accesses the database several times when files are dropped into a specific directory. Furthermore, I have a service_timer that runs every 5 minutes that also accesses the database. The issue then, is that when my service is processing a file and my service_timer is called, I end up getting an InvalidOperationError (There is already an open Data Reader).
Is there a way to create a new connection for to the database (on Microsoft SQL Server Express) so I can avoid this problem, or is there another common solution?
Thanks.
Here is the code of the function where the exception is being thrown:
DateTime start = DateTime.Now;
string SqlQuery = "SELECT COUNT (*) AS recCount FROM " + tableName + " " + whereclause;
Debug.WriteLine(thisMethod + " SqlQuery: " + SqlQuery);
myCommand = new SqlCommand(SqlQuery, this.SDB); //Execute Sql Statement
myCommand.ExecuteNonQuery();
// Create New Adapter
adapter = new SqlDataAdapter(myCommand);
adapter.SelectCommand = myCommand;
DataSet ds = new DataSet();
// Populate Adapter
adapter.Fill(ds);
foreach (DataTable dt in ds.Tables)
foreach (DataRow dr in dt.Rows)
{
recCount = Convert.ToInt32(dr["recCount"]);
}
The problem lies here
myCommand = new SqlCommand(SqlQuery, this.SDB);
You should create a new SQLConnection within the method instead of using a global.
SqlConnection newConn = new SqlConnection(connectionString);
newConn.Open();
myCommand = new SqlCommand(SqlQuery, newConn);
//Rest of logic
newConn.Close();

Bulk import from MS Access and Insert into Sql Server [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to read records from MS Access database and Insert into Sql server database, the process should be bulk insertion. I'm using asp.net/vb.net
First of all read data from Excel sheet
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/temp/") + "FileName.xlsx; Extended Properties=Excel 12.0;";
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand selectCommand = factory.CreateCommand();
selectCommand.CommandText = "SELECT ColumnNames FROM [Sheet1$]";
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
selectCommand.Connection = connection;
adapter.SelectCommand = selectCommand;
DataTable dtbl = new DataTable();
adapter.Fill(dtbl);
// Then use SQL Bulk query to insert those data
if (dtbl.Rows.Count > 0)
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destConnection))
{
bulkCopy.ColumnMappings.Add("ColumnName", "ColumnName");
bulkCopy.ColumnMappings.Add("ColumnName", "ColumnName");
bulkCopy.DestinationTableName = "DBTableName";
bulkCopy.WriteToServer(dtblNew);
}
}
private void Synchronize()
{
SqlConnection con = new SqlConnection("Database=DesktopNotifier;Server=192.168.1.100\\sql2008;User=common;Password=k25#ap;");
con.Open();
SqlDataAdapter adap = new SqlDataAdapter("SELECT * FROM CustomerData", con);
DataSet ds = new DataSet();
adap.Fill(ds, "CustomerData");
DataTable dt = new DataTable();
dt = ds.Tables["CustomerData"];
foreach (DataRow dr in dt.Rows)
{
string File = dr["CustomerFile"].ToString();
string desc = dr["Description"].ToString();
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;" + #"Data Source=D:\\DesktopNotifier\\DesktopNotifier.accdb";
OleDbConnection conn = new OleDbConnection(conString);
conn.Open();
string dbcommand = "insert into CustomerData (CustomerFile, Description) VALUES ('" + File + "', '" + desc + "')";
OleDbCommand mscmd = new OleDbCommand(dbcommand, conn);
mscmd.ExecuteNonQuery();
}
}
private void Configuration_Load(object sender, EventArgs e)
{
LoadGridData();
LoadSettings();
}
Just my two cents...
Using code like this:
DataSet ds = new DataSet();
adap.Fill(ds, "CustomerData");
You should be aware the the data adapter fill method is going to READ ALL data into memory. So if you have zillions of rows... think twice.

Categories