Save excel file in database using c# - sql-server

I have an excel file. Now I need to save data of excel file in database. What is the simplest way to do that using c# with simple example? Thank in advance

This will do what you want.
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection ExcelConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\your_path\\Import_List.xls;Extended Properties=Excel 8.0;");
ExcelConnection.Open();
string expr = "SELECT * FROM [Sheet1$]";
OleDbCommand objCmdSelect = new OleDbCommand(expr, ExcelConnection);
OleDbDataReader objDR = null;
SqlConnection SQLconn = new SqlConnection();
string ConnString = "Data Source=Your_Database_Name;Initial Catalog=Table_Name;Trusted_Connection=True;";
SQLconn.ConnectionString = ConnString;
SQLconn.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(SQLconn))
{
bulkCopy.DestinationTableName = "tblTest";
try
{
objDR = objCmdSelect.ExecuteReader();
bulkCopy.WriteToServer(objDR);
ExcelConnection.Close();
//objDR.Close()
SQLconn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}

To copy from a SQL Server table to an Excel file, try the following.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert into [Sheet1$] (id,name) values('5','e')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}
Or, with a 'Where' clause, you can have more control of the output.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Update [Sheet1$] set name = 'New Name' where id=1";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

Related

How do I export data from a datagridview/data set into an Access Database? [C#]

So my title is pretty self explanatory, so thus far I have read Microsofts Documentation and watched some Youtube videos regarding my issue here.
Firstly my project code here:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
foreach (DataRow r in dsEquipment.Tables[0].Rows)
{
DataRow dr = sQTDBDataSet.tblEquipment.NewRow();
dr[0] = r[0];
dr[1] = r[1];
dr[2] = r[2];
dr[3] = r[3];
dr[4] = r[4];
dr[5] = r[5];
dr[6] = r[6];
dr[7] = r[7];
dr[8] = r[8];
dr[9] = r[9];
dr[10] = r[10];
dr[11] = r[11];
dr[12] = r[12];
dr[13] = r[13];
dr[14] = r[14];
dr[15] = r[15];
dr[16] = r[16];
sQTDBDataSet.tblEquipment.Rows.Add(dr);
}
//tblEquipmentTableAdapter.Update(sQTDBDataSet.tblEquipment);
//tableAdapterManager.UpdateAll(sQTDBDataSet);
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
this.Validate();
this.tblEquipmentBindingSource.EndEdit();
this.tblEquipmentTableAdapter.Update(this.sQTDBDataSet.tblEquipment);
MessageBox.Show("Update successful");
}
catch (System.Exception ex)
{
MessageBox.Show("Update failed");
}
}
private void btnReadExcel_Click(object sender, EventArgs e)
{
OpenFileDialog OFD = new OpenFileDialog();
if (OFD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string strfilename = OFD.FileName;
txtFileName.Text = strfilename;
}
}
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void tblEquipmentBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.tblEquipmentBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.sQTDBDataSet);
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'sQTDBDataSet.tblEquipment' table. You can move, or remove it, as needed.
this.tblEquipmentTableAdapter.Fill(this.sQTDBDataSet.tblEquipment);
}
private void btnOpenFile_Click(object sender, EventArgs e)
{
try
{
// Establish connection between the c# application and the excel file.
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + txtFileName.Text + ";Extended Properties=Excel 12.0");
// Reading the data from the excel file.
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Equipments$]", con);
// All data from the file will be loaded into the dataset.
da.Fill(dsEquipment);
// Show in a message box how many rows of data there is.
//MessageBox.Show(dsEquipment.Tables[0].Rows.Count.ToString());
// Show the data in the data grid view.
dgEquipment.DataSource = dsEquipment.Tables[0];
}
catch
{
MessageBox.Show("Please select the SQT2 Excel sheet.");
}
}
}
}
So my first attempt at tackling the problem was this:
//tblEquipmentTableAdapter.Update(sQTDBDataSet.tblEquipment);
//tableAdapterManager.UpdateAll(sQTDBDataSet);
I get no errors but for some reason my Access Database is not showing the updates.
My second attempt was the following:
private void btnOpenFile_Click(object sender, EventArgs e)
{
try
{
// Establish connection between the c# application and the excel file.
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + txtFileName.Text + ";Extended Properties=Excel 12.0");
// Reading the data from the excel file.
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Equipments$]", con);
// All data from the file will be loaded into the dataset.
da.Fill(dsEquipment);
// Show in a message box how many rows of data there is.
//MessageBox.Show(dsEquipment.Tables[0].Rows.Count.ToString());
// Show the data in the data grid view.
dgEquipment.DataSource = dsEquipment.Tables[0];
}
catch
{
MessageBox.Show("Please select the SQT2 Excel sheet.");
}
}
Which was a seperate button and I obtained this code from Microsofts documentation and changed the variables of the dataset and the database table, no errors... yet STILL my access database is not updating!
Completely stuck right now and any help is appreciated! :)
Thank you!

How to import Excel file data into database?

I've created a form where the manager can import an Excel file to DataGridView but I'm having trouble saving it to the database.
Reason: So when the manager imports the rota Excel file to DataGridView I want the other users to see it in a different form.
My form code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace Login
{
public partial class EmployeeRota : Form
{
string con = "Data Source=dqq5ndqef2.database.windows.net;Initial Catalog=Login;Integrated Security=False;User ID=richardjacobs97;Password=;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
SqlDataAdapter sda;
SqlCommandBuilder scb;
DataTable dt;
public EmployeeRota()
{
InitializeComponent();
}
private void btnSelect_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox1.Text = openFileDialog1.FileName;
}
}
private void button1_Click(object sender, EventArgs e)
{
string PathCpnn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(PathCpnn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [" + textBox2.Text + "$]", conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
myDataAdapter.Update(dt);
}
private void EmployeeRota_Load(object sender, EventArgs e)
{
string connectionString = con;
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Rota (Id, Name, Date) Values (#Id, #Name, #Date)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
int i = 0;
i = dataGridView1.RowCount - 1;
cmd.Parameters.AddWithValue("#Id", dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#Name", dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("#Date", dataGridView1.Rows[i].Cells[0].Value);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
}
}
}
}
Database: Database pic
Form: Form pic
Any suggestions why I get this error?
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
You are receiving that error because the Load function runs when the page is first opened. You should move this into a separate functions so that it can be called at select times, maybe from a button click. This is prior to any data source being applied to the
DataGridView. You need to add the following to make sure there are rows in the table.
i = dataGridView1.RowCount - 1;
if(i<0) // Meaning that the row count was 0
{
return;
}
cmd.Parameters.AddWithValue("#Id", dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#Name", dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("#Date", dataGridView1.Rows[i].Cells[0].Value);

Additional information: Syntax error (missing operator) in query expression 'pin='

I am trying to pass database value into a another from using visual studio windows form. How do I access the data outside the while loop? and save to a string and pass that value into form2. I keep getting this error when passing to form2: Additional information: Syntax error (missing operator) in query expression 'pin='
my code for form1:
namespace ATM
{
public partial class Form1 : Form
{
String conn_string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Dro\\Desktop\\ATM\\Database11.accdb; Persist Security Info=False;";
OleDbConnection conn = null;
public int pinnumber = 3300;
public string dbpin;
public string oppin;
public Form1()
{
InitializeComponent();
}
private void button13_Click(object sender, EventArgs e)
{
runQuery();
//checks PIN is entered or not
if (textBox2.Text.Length == 0)
{
textBox2.Text = textBox2.Text + "----";
}
else if (dbpin == textBox2.Text)//checks whether pin is correct and then shows the form 2(menu)
{
Form2 menu = new Form2();
menu.Show();
this.Hide();
}
else
{
textBox1.Text = "The PIN is Incorrect! Try Again!";
}
}
private void button_click(object sender, EventArgs e)
{
if (textBox2.Text == "----")
{
textBox2.Clear();
textBox1.Clear();
}
if (textBox2.Text.Length < 4)
{
Button button = (Button)sender;
textBox2.Text = textBox2.Text + button.Text;
textBox2.PasswordChar = '*';
}
}
private void button12_Click(object sender, EventArgs e)
{
textBox2.Clear();
}
private void runQuery()
{
conn = new OleDbConnection(conn_string);
MessageBox.Show("successfully connected");
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM atmDB where pin="+textBox2.Text;
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
dbpin = dr["PIN"].ToString();
}
MessageBox.Show(dbpin);
}
}
}

Connection string. Cannot implicitly convert 'String' to 'System.Data.SqlClient.SqlConnection'

I'm getting that error in title.
For my
cmd.Connection = Conn;
I have this
public string Conn = connection.getConnection();
I'm using a windows application, how do I fix this?
Here is my complete code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication3
{
public partial class Room : Form
{
public SqlDataReader re;
public string Conn = connection.getConnection();
public Room()
{
InitializeComponent();
}
private void Room_Load(object sender, EventArgs e)
{
..
..
..
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (textBox1.Text.Length != 0 && textBox2.Text.Length != 0)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "insertToRoom";
cmd.Parameters.AddWithValue("#room_name", textBox1);
cmd.Parameters.AddWithValue("#room_rate", textBox2);
cmd.ExecuteNonQuery();
}
else
{
MessageBox.Show("Please fill in all the textbox.", "Wrong Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Try this way. First get the connection string from web.conf or app.conf and then create a sqlconnection to assign to sqlcommand.
var connectionString =
ConfigurationManager.ConnectionStrings["NameofConstringFromWebconfig"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection =new SqlConnection(connectionString);

Failing to connect to SQL Server from C#

I am trying to import excel file into SQL Server 2005 in C#, but I', getting an error.
Here's my code:
namespace excel
{
public partial class Csharp_Excel : Form
{
public Csharp_Excel()
{
InitializeComponent();
}
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
private void button1_Click(object sender, EventArgs e)
{
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
path = Path.Combine(path, "csharp-Excel.xls");
string connStr = #"Server=.\\SQLEXPRESS;Data Source= C:\\Users\\adil pc\\Documents\\Visual Studio 2008\\Projects\\excel\\excel\\bin\\Debug\\csharp-Excel.xls;Initial Catalog=RMS;Integrated Security=SSPI;";
SqlConnection con = new SqlConnection(connStr);
string strCmd = "select * from [sheet1$A1:E7]";
SqlCommand cmd = new SqlCommand(strCmd, con);
try
{
con.Open();
ds.Clear();
da.SelectCommand = cmd;
da.Fill(dt);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
}
}
private void btnsend_Click(object sender, EventArgs e)
{
}
}
The error that I am getting is:
System.Data.SqlClient.SqlException: A network-related or instance-specified error occurred while establishing a connection to SQL Server
I think I got it working I made some changes in connection string :
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\csharp-Excel.xls;Extended Properties=\"Excel 8.0;HDR=Yes;\";
it is working on demo havent implement in actual project once I do will update.

Resources