How to import MDB file, read and save in SQL - c#

I need to import .MDB file, read and save in SQL Server.
I tried this:
Method Import
protected void Btn_Importar(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (FileUpload1.PostedFile.ContentType == "application/msaccess")
{
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/Upload/") + filename);
Label1.Text = "File uploaded successfully!";
//ReadMdb();
Insert();
}
}
}
Method Insert
public void Insert()
{
string strFile = Server.MapPath("~/Upload/teste.mdb");
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFile;
var myDataTable = new DataTable();
using (var connection = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" + "data source=" + strFile))
{
connection.Open();
var query = "SELECT * FROM BOLETO";
var command = new OleDbCommand(query, connection);
var reader = command.ExecuteReader();
Conexaocs con = new Conexaocs();
con.Conexao();
SqlCommand sqlComm = new SqlCommand("INSERT INTO BOLETO (CODIGO,NF_CONTA,TEXTO) VALUES (#CODIGO, #NF_CONTA, #TEXTO)", conn);
//if (reader.HasRows)
//{
// while (reader.Read())
// {
// //ListBox1.Items.Add(reader.GetInt32(0).ToString() + " - " + reader.GetString(1));
// }
for (int i = 0; i < reader.FieldCount; i++)
{
sqlComm.Parameters.AddWithValue("#CODIGO", reader[i]);
sqlComm.Parameters.AddWithValue("#NF_CONTA", reader[i]);
sqlComm.Parameters.AddWithValue("#TEXTO", reader[i]);
sqlComm.ExecuteNonQuery();
}
connection.Close();
}
}
But, when come this point not save!
for (int i = 0; i < reader.FieldCount; i++)
{
sqlComm.Parameters.AddWithValue("#CODIGO", reader[i]);
sqlComm.Parameters.AddWithValue("#NF_CONTA", reader[i]);
sqlComm.Parameters.AddWithValue("#TEXTO", reader[i]);
sqlComm.ExecuteNonQuery();
}
Message error: System.InvalidOperationException: There are no data for the row or column
Some idea? Thanks

As Gord Thompson say you need to iterate through the rows, not the fields. Try the following (untested) code:
if (reader.HasRows)
{
while (reader.Read())
{
sqlComm.Parameters.AddWithValue("#CODIGO", reader[0]);
sqlComm.Parameters.AddWithValue("#NF_CONTA", reader[1]);
sqlComm.Parameters.AddWithValue("#TEXTO", reader[2]);
sqlComm.ExecuteNonQuery();
}
}

Não existem dados para a linha ou coluna
apparently means
There are no data for the row or column
You opened the OleDbDataReader but you didn't Read() from it. (You did once upon a time, but that while loop has been commented out.)

Related

Importing data from excelsheet file into the mysql database C#

I have the following lines of code:
protected void btnUpload_Click(object sender, EventArgs e)
{
MySqlTransaction transaction;
string ex_id = "";
string file_name = Path.GetFileName(FileUpload1.FileName);
string Excel_path = Server.MapPath("~/Excel/" + file_name);
DataTable dtExceldata = new DataTable();//just added
FileUpload1.SaveAs(Excel_path);
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
my_con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
da.Fill(dtExceldata);
if (dtExceldata.Rows.Count > 0)
{
//foreach (DataRow row in dtExceldata.Rows)
for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
{
string ex_dir = dtExceldata.Rows[i]["website_a"].ToString();
//string ex_dir = row["website_a"].ToString();
string ex_email = dtExceldata.Rows[i]["email_id"].ToString();
// string ex_email = row["email_id"].ToString();
string ex_email1 = dtExceldata.Rows[i]["email_id2"].ToString();
//string ex_email1 = row["email_id2"].ToString();
string ex_email2 = dtExceldata.Rows[i]["email_id3"].ToString();
//string ex_email2 = row["email_id3"].ToString();
string ex_company = dtExceldata.Rows[i]["company"].ToString();
//string ex_company = row["company"].ToString();
string ex_contact = dtExceldata.Rows[i]["contact_name"].ToString();
//string ex_contact = row["contact_name"].ToString();
string ex_proposal = dtExceldata.Rows[i]["proposal_status"].ToString();
// string ex_proposal = row["proposal_status"].ToString();
string ex_reason = dtExceldata.Rows[i]["reason"].ToString();
//string ex_reason = row["reason"].ToString();
int chk = 0;
int type = 0;
int dup = 0;
int dir = 0;
if (ddlwebsites.SelectedIndex != 0)
{
dir = Convert.ToInt32(ddlwebsites.SelectedValue);
if (dir == 8)
{
type = 1;
}
}
foreach (ListItem lstAssign in ddlevents.Items)
{
if (lstAssign.Selected == true)
{
chk = 1;
}
}
if (type == 1 && chk == 0)
{
evyerror.Text = "Please Select the Event!!";
return;
}
else
{
string querycomp = "", compID = "";
querycomp = "Select * from barter_company where website like '%' '" + ex_dir + "' '%'";
string connStr = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
connect = new MySqlConnection(connStr);
connect.Open();
transaction = connect.BeginTransaction();
try
{
ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
DataTable dt = clsDtResult.GetDataTable(querycomp);
if (dt.Rows.Count > 0)
{
compID = dt.Rows[0]["comp_id"].ToString();
ViewState["comp_id"] = compID;
if (type == 1)
{
dup = checkforDuplicates(Convert.ToInt32(compID));
if (dup == 1)
{
//Confirm_MP.Show();
// ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "confirmation();", true);
}
}
//return;
}
else
{
string queryStr = "insert into barter_company (comp_name,website) values(?comp,?website)";
MySqlCommand cmd = new MySqlCommand(queryStr, connect, transaction);
cmd.Parameters.AddWithValue("?comp", ex_company);
cmd.Parameters.AddWithValue("?website", ex_dir);
cmd.ExecuteNonQuery();
cmd.CommandText = "Select LAST_INSERT_ID()";
compID = cmd.ExecuteScalar().ToString();
transaction.Commit();
connect.Close();
}
}
catch
{
transaction.Rollback();
}
if (dup == 0)
{
// create a connection string with your sql database
string connStr1 = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
connect = new MySqlConnection(connStr1);
connect.Open();
DateTime date = new DateTime();
date = DateTime.ParseExact(txtsentdate.Text, "MM/dd/yyyy", null);
string SentDateString = date.ToString("yyyy/MM/dd");
//DateTime date = new DateTime();
//if (!string.IsNullOrEmpty(ex_date))
// {
//DateTime date = new DateTime();//added by chetan
//ex_date = ex_date.Split(' ')[0];//added by chetan
//date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);//added by chetan
//string SentDateString = date.ToString("yyyy/MM/dd");//added by chetan
//DateTime SentDate = Convert.ToDateTime(SentDateString).Date;//added by chetan
//// DateTime date = DateTime.Parse(ex_date);//added by chetan
// }
//date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);//added by chetan
//date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
// string SentDateString = date.ToString("yyyy/MM/dd");
transaction = connect.BeginTransaction();
try
{
string ex_uid = Session["session_barterUser_id"].ToString();
MySqlCommand cmd = new MySqlCommand("insert into barter_proposals(user_id, sent_date, website_a, email_id, email_id2, email_id3, company, contact_name, proposal_status, reason,type) values(?uid,?sentdate,?dir,?email,?email2,?email3,?comp,?cont_name,?pro_status,?reason,?type)", connect);
cmd.Parameters.AddWithValue("?uid", ex_uid);
cmd.Parameters.AddWithValue("?comp", compID);
cmd.Parameters.AddWithValue("?sentdate", SentDateString);
// command.Parameters.AddWithValue("?event", eventname);
cmd.Parameters.AddWithValue("?dir", dir);
// command.Parameters.AddWithValue("?bar_type", ddlbartertype.SelectedValue);
// command.Parameters.AddWithValue("?website_b", txtwebsite.Text);
//cmd.Parameters.AddWithValue("?comp", ex_company);
cmd.Parameters.AddWithValue("?cont_name", ex_contact);
cmd.Parameters.AddWithValue("?email", ex_email);
cmd.Parameters.AddWithValue("?email2", ex_email1);
cmd.Parameters.AddWithValue("?email3", ex_email2);
cmd.Parameters.AddWithValue("?pro_status", ex_proposal);
cmd.Parameters.AddWithValue("?reason", ex_reason);
cmd.Parameters.AddWithValue("?type", type);
// command.Parameters.AddWithValue("?type", type);
cmd.ExecuteNonQuery();
if (type == 1)
{
cmd.CommandText = "Select LAST_INSERT_ID()";
Int64 CurrentProId = Convert.ToInt64(cmd.ExecuteScalar());
int eventAssignID;
string QueryInqEventAssign = "insert into barter_propeventassign(prop_id,event_id) values(?pro_id,?event_id)";
foreach (ListItem lstAssign in ddlevents.Items)
{
if (lstAssign.Selected == true)
{
cmd = new MySqlCommand(QueryInqEventAssign, connect, transaction);
cmd.Parameters.AddWithValue("?pro_id", CurrentProId);
eventAssignID = Convert.ToInt32(lstAssign.Value);
cmd.Parameters.AddWithValue("?event_id", eventAssignID);
cmd.ExecuteNonQuery();
}
}
}//end of if
transaction.Commit();
connect.Close();
Response.Write("<script type=\"text/javascript\">alert('Proposal Added Successfully!!!');</script>");
}//end of try
catch (Exception ex)
{
transaction.Rollback();
Response.Write("<script>alert('There is an Error Ocurred:" + Server.HtmlEncode(ex.Message) + "')</script>");
}
finally
{
connect.Close();
}
}//ifdupzero
}//else
}//for//foreach
}//while //if
// dr.Close();//commented by chetan
my_con.Close();
if (System.IO.File.Exists(Excel_path))
{
System.IO.File.Delete(Excel_path);
}
}
suppose there are 2 entries in the excelsheet file.When trying to import,it is inserting those 2 rows entries into the database table.but the problem is that, the reader does not stop its execution.After reading 2 rows entry,it is reading 3rd row which is blank.i have used dr.close and it keeps on reading the rows entries which is blank.
Instead of checking if there are rows left (dr.Read()) as your loop condition, you could check if the first cell of the row is blank (dr[0].ToString() != String.Empty)
string file_name = Path.GetFileName(FileUpload1.FileName);
string Excel_path = Server.MapPath("~/Excel/" + file_name);
FileUpload1.SaveAs(Excel_path);
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
my_con.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", my_con);
OleDbDataReader dr = command.ExecuteReader();
dr.Read();
while (dr[0].ToString() != String.Empty)
{
ex_id = dr[0].ToString();
string ex_uid = dr[1].ToString();
//get second row data and assign it ex_name variable
string ex_date = dr[2].ToString();
//get thirdt row data and assign it ex_name variable
string ex_dir = dr[3].ToString();
//get first row data and assign it ex_location variable
string ex_email = dr[4].ToString();
string ex_email1 = dr[5].ToString();
string ex_email2 = dr[6].ToString();
//string ex_company = dr[7].ToString();
string ex_company = dr[7].ToString();
string ex_contact = dr[8].ToString();
string ex_proposal = dr[9].ToString();
string ex_reason = dr[10].ToString();
...............
//Insert operation
...............
dr.Read();
}
dr.close();
my_con.close();
The premise of course is, that the first column is always filled if the rest of the row isn't blank.
If that isn't the case you can also check other columns in the loop condition.
there is various way of doing that
you can load excel data to datatable and then you can for loop for each row with perticular column name like this
string file_name = Path.GetFileName(FileUpload1.FileName);
string Excel_path = Server.MapPath("~/Excel/" + file_name);
DataTable dtExceldata = new DataTable();
FileUpload1.SaveAs(Excel_path);
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended
Properties=Excel 8.0;Persist Security Info=False");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
da.Fill(dtExceldata);
if(dtExceldata.Rows.Count>0)
{
for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
{
//assign value to variable
//like below
//string ex_uid = dtExceldata.Rows[i]["columnName"];
//then insert operation here
}
}
see this excel file
and the datatable in c#
this loop will repeat for only number of row in datatable then also i practically tried this and it only loop for number of row (e.g two times) but i found a bug that if you will enter two row then five blank row then some data it will give you blank value in data table check your excel file there may some blank value as shown in attechment
then also you can skip blank value by checking null value in row like this
for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
{
if (!String.IsNullOrEmpty(Convert.ToString(dtExceldata.Rows[i]["fieldvalues"])))
{
//assign value to variable
//like below
//string ex_uid = dtExceldata.Rows[i]["columnName"];
//then insert operation here
}
}

how to saved different sheet from excel file to mysql database

I have a code that importing and displaying a excel file to datagridview and I'm wondering if you help me to how can I save those sheet from my excel file to my database in mysql?? My sheet name are 1st grading, 2nd grading and attendance, I'm using c#. Anyway here's my code:
private void btnSaved_Click(object sender, EventArgs e)
{
int qtr = 0;
string att_qtr = "ATTENDANCE";
MySqlConnection con = new MySqlConnection("Server = DESKTOP-9H7QBOH; Database = sti_spms; UID = root; Password = 1234;");
try
{
string query = "INSERT INTO tbl_secondsem_grades(STUDENT_NO, NAME, SUBJECT, SECTION, GRADE, INITIAL_GRADE, QTR)" + "Values(#STUDENT_NO, #NAME, #SUBJECT, #SECTION, #GRADE, #INITIAL_GRADE, #QTR)";
query += "INSERT INTO tbl_attendance(STUDENT_ID, NAME, SUBJECT, SECTION, TOTAL_ABSENCES)" + "Values(#STUDENT_ID, #NAME, #SUBJECT, #SECTION, #TOTAL_ABSENCES)";
MySqlCommand cmd = new MySqlCommand(query, con);
DataTable dt = new DataTable();
con.Open();
for (int i = 0; i < dataGridView1.Rows.Count -1; i++)
{
if(quarter.Equals("1st QTR"))
{
qtr = 1;
}
else if(quarter.Equals("2nd QTR"))
{
qtr = 2;
}
else if(quarter.Equals("3rd QTR"))
{
qtr = 3;
}
else if(quarter.Equals("4th QTR"))
{
qtr = 4;
}
else if (quarter.Equals("ATTENDANCE"))
{
att_qtr = "ATTENDANCE";
}
else
{
MessageBox.Show("Error!");
}
//int num = Convert.ToInt32(dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString());
cmd.Parameters.AddWithValue("#STUDENT_NO", dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString());
cmd.Parameters.AddWithValue("#NAME", dataGridView1.Rows[i].Cells["NAME"].Value.ToString());
cmd.Parameters.AddWithValue("#SUBJECT", dataGridView1.Rows[i].Cells["SUBJECT"].Value.ToString());
cmd.Parameters.AddWithValue("#SECTION", dataGridView1.Rows[i].Cells["SECTION"].Value.ToString());
cmd.Parameters.AddWithValue("#INITIAL_GRADE", dataGridView1.Rows[i].Cells["INITIAL GRADE"].Value.ToString());
cmd.Parameters.AddWithValue("#GRADE", dataGridView1.Rows[i].Cells["QG"].Value.ToString());
cmd.Parameters.AddWithValue("#QTR", qtr);
cmd.Parameters.AddWithValue("#STUDENT_NO", dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString());
cmd.Parameters.AddWithValue("#NAME", dataGridView1.Rows[i].Cells["NAME"].Value.ToString());
cmd.Parameters.AddWithValue("#SUBJECT", dataGridView1.Rows[i].Cells["SUBJECT"].Value.ToString());
cmd.Parameters.AddWithValue("#SECTION", dataGridView1.Rows[i].Cells["SECTION"].Value.ToString());
cmd.Parameters.AddWithValue("#Total_Absences", dataGridView1.Rows[i].Cells["Total_Absences"].Value.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
catch (Exception ex)
{
MessageBox.Show("Data Sucessfully Saved!");
}
}
Quickie partial
...
MySqlCommand cmd = new MySqlCommand(query, con);
DataTable dt = new DataTable();
cmd.Paramters.Add("#STUDENT_NO", MySqlDbType.Int); .. guessing this is an int - otherwise choose type
cmd.Paramters.Add("#NAME", MySqlDbType.String);
... // add rest here
con.Open();
...
for (.. ) {
...
int studentno;
int.TryParse(dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString(), out studentno);
cmd.Paramters["#STUDENT_NO"].Value = studentno;
cmd.Paramters["#NAME"].Value = dataGridView1.Rows[i].Cells["NAME"].Value.ToString();
...
}

Updating data in listbox from datatable

I want to show data from data table on form_load using list box, and later update that data from list box on button click by Insert command. Function for that is fill_List(). This is my code:
OleDbConnection konekcija;
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
public Form2()
{
InitializeComponent();
string putanja = Environment.CurrentDirectory;
string[] putanjaBaze = putanja.Split(new string[] { "bin" }, StringSplitOptions.None);
AppDomain.CurrentDomain.SetData("DataDirectory", putanjaBaze[0]);
konekcija = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=|DataDirectory|\B31Autoplac.accdb");
}
void fill_List()
{
konekcija.Open();
OleDbCommand komPrikaz = new OleDbCommand("SELECT * FROM GORIVO ORDER BY GorivoID ASC", konekcija);
adapter.SelectCommand = komPrikaz;
adapter.Fill(dt);
listBox1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
string pom;
pom = dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString() + " " + dt.Rows[i][2];
listBox1.Items.Add(pom);
}
konekcija.Close();
}
private void Form2_Load(object sender, EventArgs e)
{
fill_List();
}
private void btnUpisi_Click(object sender, EventArgs e)
{
string s1, s2, s3;
s1 = tbSifra.Text;
s2 = tbNaziv.Text;
s3 = tbOpis.Text;
string Upisi = "INSERT INTO GORIVO (GorivoID, Naziv, Opis) VALUES (#GorivoID, #Naziv, #Opis)";
OleDbCommand komUpisi = new OleDbCommand(Upisi, konekcija);
komUpisi.Parameters.AddWithValue("#GorivoID", s1);
komUpisi.Parameters.AddWithValue("#Naziv", s2);
komUpisi.Parameters.AddWithValue("#Opis", s3);
string Provera = "SELECT COUNT (*) FROM GORIVO WHERE GorivoID=#GorivoID";
OleDbCommand komProvera = new OleDbCommand(Provera, konekcija);
komProvera.Parameters.AddWithValue("#GorivoID", s1);
try
{
konekcija.Open();
int br = (int)komProvera.ExecuteScalar();
if(br==0)
{
komUpisi.ExecuteNonQuery();
MessageBox.Show("Podaci su uspesno upisani u tabelu i bazu.", "Obavestenje");
tbSifra.Text = tbNaziv.Text = tbOpis.Text = "";
}
else
{
MessageBox.Show("U bazi postoji podatak sa ID = " + tbSifra.Text + ".", "Obavestenje");
}
}
catch (Exception ex1)
{
MessageBox.Show("Greska prilikom upisa podataka. " + ex1.ToString(), "Obavestenje");
}
finally
{
konekcija.Close();
fill_List();
}
}
Instead of this
It shows me this (added duplicates with new data)
Is there a problem in my function or somewhere else?
Another bug caused by global variables.
You are keeping a global variable for the DataTable filled by the fill_list method. This datatable is never reset to empty when you call fill_list, so at every call you add another set of rows to the datatable and then transfer this data inside the listbox. Use a local variable.
But the same rule should be applied also to the OleDbConnection and OleDbCommand. There is no need to keep global instances of them. Creating an object is really fast and the convenience to avoid global variables is better than the little nuisance to create an instance of the connection or the command.
void fill_List()
{
using(OleDbConnection konekcija = new OleDbConnection(......))
using(OleDbCommand komPrikaz = new OleDbCommand("SELECT * FROM GORIVO ORDER BY GorivoID ASC", konekcija))
{
DataTable dt = new DataTable();
konekcija.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(komPrikaz);
adapter.Fill(dt);
listBox1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
string pom;
pom = dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString() + " " + dt.Rows[i][2];
listBox1.Items.Add(pom);
}
}
}
Clear your DataTable before filling it again.
void fill_List()
{
konekcija.Open();
OleDbCommand komPrikaz = new OleDbCommand("SELECT * FROM GORIVO ORDER BY GorivoID ASC", konekcija);
adapter.SelectCommand = komPrikaz;
dt.Clear(); // clear here
adapter.Fill(dt);
listBox1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
string pom;
pom = dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString() + " " + dt.Rows[i][2];
listBox1.Items.Add(pom);
}
konekcija.Close();
}

Firebird dataReader

I would like to see all of the data with column names in my logfile.
private static void ExecuteSQL()
{
string conn = "User ID=SYSDBA;Password=masterkey;Database=XX.18.137.XXX:C:/ER.TDB;DataSource==XX.18.137.XXX;Charset=NONE;";
FbConnection myConnection = new FbConnection(conn);
FbDataReader myReader = null;
string sql = "SELECT * FROM RDB$RELATIONS";
FbCommand myCommand = new FbCommand(sql, myConnection);
try
{
myConnection.Open();
myCommand.CommandTimeout = 0;
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
// Log.WriteLog(myReader["rdb$relation_name"].ToString());
}
myConnection.Close();
}
catch (Exception e)
{
Log.WriteLog(e.ToString());
}
}
Right now it's only showing me the rdb$relation_name column.
I want to check the different tables for which I don't have the column's name.
All you need to do is iterate over all fields printing their names before iterating the results:
private static void ExecuteSQL()
{
string conn = "User ID=SYSDBA;Password=masterkey;Database=XX.18.137.XXX:C:/ER.TDB;DataSource==XX.18.137.XXX;Charset=NONE;";
FbConnection myConnection = new FbConnection(conn);
FbDataReader myReader = null;
string sql = "SELECT * FROM RDB$RELATIONS";
FbCommand myCommand = new FbCommand(sql, myConnection);
try
{
myConnection.Open();
myCommand.CommandTimeout = 0;
myReader = myCommand.ExecuteReader();
// 1. print all field names
for (int i = 0; i < myReader.FieldCount; i++)
{
Log.WriteLog(myReader.GetName(i));
}
// 2. print each record
while (myReader.Read())
{
// 3. for each record, print every field value
for (int i = 0; i < myReader.FieldCount; i++)
{
Log.WriteLog(myReader[i].ToString());
}
}
myConnection.Close();
}
catch (Exception e)
{
Log.WriteLog(e.ToString());
}
}
I am pretty sure, that this will give ugly output as it prints every output to a new line. You should be able to change this to print the fields and each record in rows.
public static List<string> GetColumnNames(string queryString)
{
string result = string.Empty;
List<string> listOfColumns = new List<string>();
try
{
using (FbConnection conn = new FbConnection(connString))
{
conn.Open();
using (FbCommand cmd = new FbCommand(queryString, conn))
{
// Call Read before accessing data.
FbDataReader reader = cmd.ExecuteReader();
if (reader.FieldCount > 0)
{
for (int i = 0; i < reader.FieldCount; i++)
{
listOfColumns.Add(reader.GetName(i));
}
}
}
}
}
catch (Exception e)
{
BinwatchLogging.Log(e);
}
return listOfColumns;
// return result;
}
where querystring is your query (eg: select * from yourtablename) and connstring is your firebird connectionstring

Uploading an Excel sheet and importing the data into SQL Server database

I am developing this simple application to upload an Excel file (.xlsx) and import the data present in that Excel worksheet into a SQL Server Express database in .NET
I'm using the following code on click of the import button after browsing and selecting the file to do it.
protected void Button1_Click(object sender, EventArgs e)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
//file upload path
string path = FileUpload1.PostedFile.FileName;
//string path="C:\\ Users\\ Hemant\\Documents\\example.xlsx";
//Create connection string to Excel work book
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
But the code doesn't run when I use
string path = FileUpload1.PostedFile.FileName;`
and even
string path="C:\ Users\ Hemant\Documents\example.xlsx";`
The dReader is unable to take the path in this format.
It is only able to take path in the following format
string path="C:\\ Users\\ Hemant\\Documents\\example.xlsx";
i.e. with the the \\ in the path.For which I have to hard code the path but we have to browse the file.
So,can any one please suggest a solution to use the path taken by the FileUpload1 to import the data?
You are dealing with a HttpPostedFile; this is the file that is "uploaded" to the web server. You really need to save that file somewhere and then use it, because...
...in your instance, it just so happens to be that you are hosting your website on the same machine the file resides, so the path is accessible. As soon as you deploy your site to a different machine, your code isn't going to work.
Break this down into two steps:
1) Save the file somewhere - it's very common to see this:
string saveFolder = #"C:\temp\uploads"; //Pick a folder on your machine to store the uploaded files
string filePath = Path.Combine(saveFolder, FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
Now you have your file locally and the real work can be done.
2) Get the data from the file. Your code should work as is but you can simply write your connection string this way:
string excelConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 12.0";", filePath);
You can then think about deleting the file you've just uploaded and imported.
To provide a more concrete example, we can refactor your code into two methods:
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{
string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
You could simply then call SaveFileToDatabase(GetLocalFilePath(#"C:\temp\uploads", FileUpload1));
Consider reviewing the other Extended Properties for your Excel connection string. They come in useful!
Other improvements you might want to make include putting your Sql Database connection string into config, and adding proper exception handling. Please consider this example for demonstration only!
Not sure why the file path is not working, I have some similar code that works fine.
But if with two "\" it works, you can always do path = path.Replace(#"\", #"\\");
You can use OpenXml SDK for *.xlsx files. It works very quickly. I made simple C# IDataReader implementation for this sdk. See here. Now you can easy import excel file to sql server database using SqlBulkCopy. It uses small memory because it reads by SAX(Simple API for XML) method (OpenXmlReader)
Example:
private static void DataReaderBulkCopySample()
{
using (var reader = new ExcelDataReader(#"test.xlsx"))
{
var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i)).ToArray();
DataHelper.CreateTableIfNotExists(ConnectionString, TableName, cols);
using (var bulkCopy = new SqlBulkCopy(ConnectionString))
{
// MSDN: When EnableStreaming is true, SqlBulkCopy reads from an IDataReader object using SequentialAccess,
// optimizing memory usage by using the IDataReader streaming capabilities
bulkCopy.EnableStreaming = true;
bulkCopy.DestinationTableName = TableName;
foreach (var col in cols)
bulkCopy.ColumnMappings.Add(col, col);
bulkCopy.WriteToServer(reader);
}
}
}
Try Using
string filename = Path.GetFileName(FileUploadControl.FileName);
Then Save the file at specified location using:
FileUploadControl.PostedFile.SaveAs(strpath + filename);
public async Task<HttpResponseMessage> PostFormDataAsync() //async is used for defining an asynchronous method
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var fileLocation = "";
string root = HttpContext.Current.Server.MapPath("~/App_Data");
MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root); //Helps in HTML file uploads to write data to File Stream
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName); //Gets the file name
var filePath = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2); //File name without the path
File.Copy(file.LocalFileName, file.LocalFileName + filePath); //Save a copy for reading it
fileLocation = file.LocalFileName + filePath; //Complete file location
}
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, recordStatus);
return response;
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
public void ReadFromExcel()
{
try
{
DataTable sheet1 = new DataTable();
OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder();
csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
csbuilder.DataSource = fileLocation;
csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
string selectSql = #"SELECT * FROM [Sheet1$]";
using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection))
{
connection.Open();
adapter.Fill(sheet1);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
A proposed solution will be:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
CreateXMLFile();
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand cmd = new SqlCommand("bulk_in", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#account_det", sw_XmlString.ToString ());
int i= cmd.ExecuteNonQuery();
if(i>0)
{
Label1.Text = "File Upload successfully";
}
else
{
Label1.Text = "File Upload unsuccessfully";
return;
}
con.Close();
}
catch(SqlException ex)
{
Label1.Text = ex.Message.ToString();
}
}
public void CreateXMLFile()
{
try
{
M_Filepath = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
fileExtn = Path.GetExtension(M_Filepath);
strGuid = System.Guid.NewGuid().ToString();
fNameArray = M_Filepath.Split('.');
fName = fNameArray[0];
xlRptName = fName + "_" + strGuid + "_" + DateTime.Now.ToShortDateString ().Replace ('/','-');
fileName = xlRptName.Trim() + fileExtn.Trim() ;
FileUpload1.PostedFile.SaveAs(ConfigurationManager.AppSettings["ImportFilePath"]+ fileName);
strFileName = Path.GetFileName(FileUpload1.PostedFile.FileName).ToUpper() ;
if (((strFileName) != "DEMO.XLS") && ((strFileName) != "DEMO.XLSX"))
{
Label1.Text = "Excel File Must be DEMO.XLS or DEMO.XLSX";
}
FileUpload1.PostedFile.SaveAs(System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName);
lstrFilePath = System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName;
if (strFileName == "DEMO.XLS")
{
strConn = "Provider=Microsoft.JET.OLEDB.4.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";
}
if (strFileName == "DEMO.XLSX")
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 12.0;HDR=YES;'";
}
strSQL = " Select [Name],[Mobile_num],[Account_number],[Amount],[date_a2] FROM [Sheet1$]";
OleDbDataAdapter mydata = new OleDbDataAdapter(strSQL, strConn);
mydata.TableMappings.Add("Table", "arul");
mydata.Fill(dsExcl);
dsExcl.DataSetName = "DocumentElement";
intRowCnt = dsExcl.Tables[0].Rows.Count;
intColCnt = dsExcl.Tables[0].Rows.Count;
if(intRowCnt <1)
{
Label1.Text = "No records in Excel File";
return;
}
if (dsExcl==null)
{
}
else
if(dsExcl.Tables[0].Rows.Count >= 1000 )
{
Label1.Text = "Excel data must be in less than 1000 ";
}
for (intCtr = 0; intCtr <= dsExcl.Tables[0].Rows.Count - 1; intCtr++)
{
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Name"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Name"].ToString();
}
if (strValid == "")
{
Label1.Text = "Name should not be empty";
return;
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Mobile_num"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Mobile_num"].ToString();
}
if (strValid == "")
{
Label1.Text = "Mobile_num should not be empty";
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Account_number"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Account_number"].ToString();
}
if (strValid == "")
{
Label1.Text = "Account_number should not be empty";
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Amount"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Amount"].ToString();
}
if (strValid == "")
{
Label1.Text = "Amount should not be empty";
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["date_a2"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["date_a2"].ToString();
}
if (strValid == "")
{
Label1.Text = "date_a2 should not be empty";
}
else
{
strValid = "";
}
}
}
catch
{
}
try
{
if(dsExcl.Tables[0].Rows.Count >0)
{
dr = dsExcl.Tables[0].Rows[0];
}
dsExcl.Tables[0].TableName = "arul";
dsExcl.WriteXml(sw_XmlString, XmlWriteMode.IgnoreSchema);
}
catch
{
}
}`enter code here`
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
protected void Button1_Click(object sender, EventArgs e)
{
//Upload and save the file
string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
excel_con.Open();
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)) });
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["dbcn"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.Table1";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("Sl", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
}
}
Copy this in web config
<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
<add name="Excel07+ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
you can also refer this link : https://athiraji.blogspot.com/2019/03/how-to-upload-excel-fle-to-database.html
protected void btnUpload_Click(object sender, EventArgs e)
{
divStatusMsg.Style.Add("display", "none");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "";
ViewState["Fuletypeidlist"] = "0";
grdExcel.DataSource = null;
grdExcel.DataBind();
if (Page.IsValid)
{
bool logval = true;
if (logval == true)
{
String img_1 = fuUploadExcelName.PostedFile.FileName;
String img_2 = System.IO.Path.GetFileName(img_1);
string extn = System.IO.Path.GetExtension(img_1);
string frstfilenamepart = "";
frstfilenamepart = "DateExcel" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
UploadExcelName.Value = frstfilenamepart + extn;
fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/DateExcel/") + "/" + UploadExcelName.Value);
string PathName = Server.MapPath("~/Emp/DateExcel/") + "\\" + UploadExcelName.Value;
GetExcelSheetForEmp(PathName, UploadExcelName.Value);
if ((grdExcel.HeaderRow.Cells[0].Text.ToString() == "CODE") && grdExcel.HeaderRow.Cells[1].Text.ToString() == "SAL")
{
GetExcelSheetForEmployeeCode(PathName);
}
else
{
divStatusMsg.Style.Add("display", "");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "ERROR !!...Please Upload Excel Sheet in header Defined Format ";
}
}
}
}
private void GetExcelSheetForEmployeeCode(string filename)
{
int count = 0;
int selectedcheckbox = 0;
string empcodeexcel = "";
string empcodegrid = "";
string excelFile = "Employee/DateExcel" + filename;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet ds = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + filename;
// Create connection.
objConn = new OleDbConnection(connString);
// Opens connection with the database.
if (objConn.State == ConnectionState.Closed)
{
objConn.Open();
}
// Get the data table containing the schema guid, and also sheet names.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
// And respective data will be put into dataset table
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT DISTINCT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(ds, "TABLE");
if (ds.Tables[0].ToString() != null)
{
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
for (int k = 0; k < GrdEmplist.Rows.Count; k++)
{
empcodeexcel = ds.Tables[0].Rows[j][0].ToString();
date.Value = ds.Tables[0].Rows[j][1].ToString();
Label lbl_EmpCode = (Label)GrdEmplist.Rows[k].FindControl("lblGrdCode");
empcodegrid = lbl_Code.Text;
CheckBox chk = (CheckBox)GrdEmplist.Rows[k].FindControl("chkSingle");
TextBox txt_Sal = (TextBox)GrdEmplist.Rows[k].FindControl("txtSal");
if ((empcodegrid == empcodeexcel) && (date.Value != ""))
{
chk.Checked = true;
txt_Sal.Text = date.Value;
selectedcheckbox = selectedcheckbox + 1;
lblSelectedRecord.InnerText = selectedcheckbox.ToString();
count++;
}
if (chk.Checked == true)
{
}
}
}
}
}
i++;
}
}
catch (Exception ex)
{
ShowMessage(ex.Message.ToString(), 0);
}
finally
{
// Clean up.
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
{
string excelFile = "DateExcel/" + PathName;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet dss = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dss, "TABLE");
}
i++;
}
grdExcel.DataSource = dss.Tables[0].DefaultView;
grdExcel.DataBind();
lblTotalRec.InnerText = Convert.ToString(grdExcel.Rows.Count);
}
catch (Exception ex)
{
ViewState["Fuletypeidlist"] = "0";
grdExcel.DataSource = null;
grdExcel.DataBind();
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
bool logval = true;
if (logval == true)
{
String img_1 = fuUploadExcelName.PostedFile.FileName;
String img_2 = System.IO.Path.GetFileName(img_1);
string extn = System.IO.Path.GetExtension(img_1);
string frstfilenamepart = "";
frstfilenamepart = "Emp" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
UploadExcelName.Value = frstfilenamepart + extn;
fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/EmpExcel/") + "/" + UploadExcelName.Value);
string PathName = Server.MapPath("~/Emp/EmpExcel/") + "\\" + UploadExcelName.Value;
GetExcelSheetForEmp(PathName, UploadExcelName.Value);
}
}
}
private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
{
string excelFile = "EmpExcel/" + PathName;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet dss = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dss, "TABLE");
}
i++;
}
grdByExcel.DataSource = dss.Tables[0].DefaultView;
grdByExcel.DataBind();
}
catch (Exception ex)
{
ViewState["Fuletypeidlist"] = "0";
grdByExcel.DataSource = null;
grdByExcel.DataBind();
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}

Categories