How can I paste selected data into another Excel sheet using OLEDB? - c#

I have 2 Excel sheets. My requirement is, I have to copy all the data from one Excel sheet to another. Below is code snippet for the same, below code is copying and pasting all the data from one sheet to another in Excel, but its not pasting the data from A1 range.
I want the selected data to be pasted in another Excel sheet starting from 1st row. Also, I want to delete and insert fresh data every time the button is clicked, instead of appending into the same. Please help.
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.Common;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace TestExcelSheet
{
public partial class Form1 : Form
{
string path = #"C:\Users\Bhawesh\Documents\Visual Studio 2010\Projects\TestExcelSheet\DataValidationTest.xlsx";
string pathdestination = #"C:\Users\Bhawesh\Documents\Visual Studio 2010\Projects\TestExcelSheet\DataValidationTest - updated.xlsx";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//Source Path
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand selectCommand = factory.CreateCommand();
selectCommand.CommandText = "SELECT [Job Code], [Job Name],Format([Start Date],'MM-DD-YYYY') as [Start Date], Format([End Date],'MM-DD-YYYY') as [End Date] FROM [Job$]";
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
selectCommand.Connection = connection;
adapter.SelectCommand = selectCommand;
DataSet Job = new DataSet();
adapter.Fill(Job);
for (int iRowCount = 0; iRowCount <= Job.Tables[0].Rows.Count; iRowCount++)
{
string JobCode = "";
string JobName = "";
string StartDate = "";
string EndDate = "";
JobCode = Job.Tables[0].Rows[iRowCount]["Job Code"].ToString().Trim();
JobName = Job.Tables[0].Rows[iRowCount]["Job Name"].ToString().Trim();
StartDate = Job.Tables[0].Rows[iRowCount]["Start Date"].ToString().Trim();
EndDate = Job.Tables[0].Rows[iRowCount]["End Date"].ToString().Trim();
//Destination Path
string connectionStringdest = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathdestination + ";Extended Properties=Excel 12.0;";
DbProviderFactory factorydest = DbProviderFactories.GetFactory("System.Data.OleDb");
DbDataAdapter adapterdest = factorydest.CreateDataAdapter();
DbCommand insertCommand = factorydest.CreateCommand();
DbConnection connectiondest = factorydest.CreateConnection();
connectiondest.ConnectionString = connectionStringdest;
insertCommand.Connection = connectiondest;
adapterdest.InsertCommand = insertCommand;
if (connectiondest.State == ConnectionState.Closed)
{
connectiondest.Open();
}
if (Job.Tables.Count > 0 && Job.Tables[0].Rows.Count > 0)
{
insertCommand.CommandText = "Insert into [Job_updated$] values ('" + JobCode + "', '" + JobName + "', '" + StartDate + "', '" + EndDate + "') ";
//insertCommand.CommandText = "UPDATE [Job_updated$E1:E1] SET F1='MyNewCol';";
insertCommand.ExecuteNonQuery();
insertCommand.Dispose();
}
connectiondest.Close();
dataGridView1.DataSource = Job.Tables[0].DefaultView;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

but its not pasting the data from A1 range because first row is considered to be the headers for the table (sheet)
either create them manually or use getRange to do that.
// Create an array for the headers and add it to cells A1:C1.
object[] objHeaders = {"Order ID", "Amount", "Tax"};
m_objRange = m_objSheet.get_Range("A1", "C1");
m_objRange.Value = objHeaders;
in order to insert new data each time perform a delete command before inserting
oleDb does not sopport the delete command
Excel.Range ran = (Excel.Range)sheet.Rows[5, Type.Missing];
ran.Select();
ran.Delete(Excel.XlDirection.xlUp);
check this link for more functions on excel file Here

Related

Import Excel to Access with c#

I've imported an Excel file and displayed the data using a datagrid view, but I want also to save in to my MS Access database.
Can it be done with OleDbCommand and select * into ?
Below is the code for my import from an Excel file; for the import I created it based on another post here:
private void BtnImport1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openfile1 = new OpenFileDialog();
openfile1.Filter = "Excel Files | *.xlsx; *.xls; *.xlsm";
openfile1.Title = "Seleccione el archivo de Excel";
if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (openfile1.FileName.Equals("") == false)
{
this.tBox1.Text = openfile1.FileName;
Ruta = openfile1.FileName;
}
}
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Ruta + ";Extended Properties = \"Excel 12.0; HDR=YES;\" ; ";
OleDbConnection con = new OleDbConnection(constr);
OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter("Select * From [Hoja 1$]", con);
DataTable dt1Excel = new DataTable();
MyDataAdapter.Fill(dt1Excel);
dataGridView1.DataSource = dt1Excel;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Try it like this and feedback.
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.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//here is a sample code which reads an Excel file Sheet1 which has 2 columns
//And inserts the same into an access table
//Change the file names, sheet name, table names and column names as per your requirements
//File Names, replae with your file names
string fileNameExcel = #"C:\your_path_here\Book1.xls";
string fileNameAccess = #"C:\your_path_here\Database1.mdb";
//Connection string for Excel
string connectionStringExcel =
string.Format("Data Source= {0};Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;", fileNameExcel);
//Connection string for Access
string ConnectionStringAccess =
string.Format("Data Source= {0}; Provider=Microsoft.Jet.OLEDB.4.0; Persist security Info = false", fileNameAccess);
//Connection object for Excel
OleDbConnection connExcel = new OleDbConnection(connectionStringExcel);
//Connection object for Access
OleDbConnection connAccess = new OleDbConnection(ConnectionStringAccess);
//Command object for Excel
OleDbCommand cmdExcel = connExcel.CreateCommand();
cmdExcel.CommandType = CommandType.Text;
cmdExcel.CommandText = "SELECT * FROM [Sheet1$]";
//Command object for Access
OleDbCommand cmdAccess = connAccess.CreateCommand();
cmdAccess.CommandType = CommandType.Text;
cmdAccess.CommandText = "INSERT INTO Table1 (Column1, Column2) VALUES(#column1, #column2)";
//Add parameter to Access command object
OleDbParameter param1 = new OleDbParameter("#column1", OleDbType.VarChar);
cmdAccess.Parameters.Add(param1);
OleDbParameter param2 = new OleDbParameter("#column2", OleDbType.VarChar);
cmdAccess.Parameters.Add(param2);
//Open connections
connExcel.Open();
connAccess.Open();
//Read Excel
OleDbDataReader drExcel = cmdExcel.ExecuteReader();
while (drExcel.Read())
{
//Assign values to access command parameters
param1.Value = drExcel[0].ToString();
param2.Value = drExcel[1].ToString();
//Insert values in access
cmdAccess.ExecuteNonQuery();
}
//close connections
connAccess.Close();
connExcel.Close();
}
}
}

How to store Arabic language values from web-service in database

I'm trying to store some Arabic values I got from a web service, but when I select them from the database and show them in a DataGridView it just shows "?????". The three columns in the database are nvarchar(50). How should I be storing them?
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.Xml;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
string user = "gamal";
string p1 = "GAM123";
string p2 = "GAM123";
string sdate = "05152014000000";
string edate = "05182014235959";
string node = "232641";
string group = "Al Ahsa - ???????";
string Compress = "";
string m_d = "sa";
string lang = "1";
DataSet ds = new DataSet();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
test_ws.ppppWebServiceSoapClient ws =
new test_ws.ppppWebServiceSoapClient("pppp Report Web ServiceSoap");
ds = ws.GetGroups(user, p1, p2);
DataSet ds_ra = new DataSet();
ds_ra = ws.RegionAlarm(user, p1, p2, sdate, edate, node, group, Compress, m_d, lang);
ds_ra.WriteXml("region_alarm.xml");
string connetionString = null;
SqlConnection connection;
SqlCommand command ;
SqlDataAdapter adpter = new SqlDataAdapter();
string sql = null;
string ID = null;
string nodegroup = null;
string nodecount = null;
connetionString = #"Server=.\SQLEXPRESS; DataBase=hhhh; Integrated Security=True;";
connection = new SqlConnection(connetionString);
int i = 0;
connection.Open();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
ID = ds.Tables[0].Rows[i].ItemArray[0].ToString();
nodegroup = ds.Tables[0].Rows[i].ItemArray[1].ToString();
nodecount = ds.Tables[0].Rows[i].ItemArray[2].ToString();
sql = "insert into groups (id,nodegroup,nodecount)
values(" + ID + ",'" + nodegroup + "'," + nodecount + ")";
command = new SqlCommand(sql, connection);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
}
sql = "select * from groups";
command = new SqlCommand(sql, connection);
adpter.SelectCommand = command;
adpter.SelectCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
adpter.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
MessageBox.Show("Done ..تم ");
}
}
}
After ensuring the NodeGroup column in your table is an NVARCHAR(), use parameters instead of concatenation, for both preventing SQL injection, and to make sure your data types are properly set. When you were concatenating the sql, the string literal was a varchar, unless you put an N in front of the literal.
sql = "insert into groups (id,nodegroup,nodecount)
values(#ID,#NodeGroup, #NodeCount)";
command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#ID", id);
command.Parameters.AddWithValue("#NodeGroup", nodegroup);
command.Parameters.AddWithValue("#NodeCroup", nodecount);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
Change this:
values(" + ID + ",'" + nodegroup + "'," + nodecount + ")";
into
values(" + ID + ", N'" + nodegroup + "'," + nodecount + ")";
However, you should really be using parameters instead of building an SQL string with the values in it. That will get you around all of the escaping issues.
When inserting in to database with inline sql you have to prefix the nvarchar value with 'N'. For example: insert into mytable (col1) values (N'myvalue')

reading one record from access in C#

My requirement is to read Date column from access file and use one value to append it to a file name, so as to create file with date timestamp using the db value.
I am trying following approach but it gives me exception "No data exists for the row/column":
here's the code
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbConnection conn1 = new OleDbConnection(connectionString);
string dt = "SELECT top 1 Date FROM Events";
OleDbCommand cmd1 = new OleDbCommand(dt, conn1);
conn1.Open();
OleDbDataReader rdr = cmd1.ExecuteReader();
string time_stmp = rdr.GetInt32(0).ToString();
rdr.Close();
conn1.Close();
string path = text_dir + "\\" + time_stmp + "_" + "BWC_Ejournal.txt";
You'll need to call the Read() method on the OleDbDataReader object before accessing its data.
E.g.
OleDbDataReader rdr = cmd1.ExecuteReader();
string time_stmp = "";
if(rdr.Read())
{
time_stmp = rdr.GetInt32(0).ToString();
}
else
{
//handle no data situation here
}
This will also allow to handle a situation where no data is returned more gracefully too.
DATE is a reserved word in ACE/Jet SQL. Try this instead:
string dt = "SELECT TOP 1 [Date] FROM Events";
Edit
On taking a closer look at your code I notice that you create the OleDbCommand object before the connection is opened. I've seen that cause problems as well. FWIW, the following code works for me:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
namespace oleDbTest
{
class Program
{
static void Main(string[] args)
{
using (var con = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=C:\__tmp\main.accdb;"))
{
con.Open();
using (var cmd = new OleDbCommand(
"SELECT TOP 1 [Date] FROM [Events]", con))
{
string time_stmp = Convert.ToDateTime(cmd.ExecuteScalar()).ToString("yyyyMMdd");
Console.WriteLine(time_stmp.ToString());
}
con.Close();
}
Console.WriteLine("Done.");
System.Threading.Thread.Sleep(2000);
}
}
}

custom query for datagridview

I am currently building an application in C#. In this application, people give values in a label and ​​that values will be saved in a database. This also works at the moment. What I want is the following:
The people can see their own values back in a datagridview. If I do this with the wizard of the datagridview I can't select label2.Text(this is the customerID).
The query I used below is the following:
SELECT * FROM prestaties WHERE gebruikerid = '" + label1.Text + "'";
But it doesn't work. I don't see anything in my datagrid.
Sorry for my bad English. I hope you can understand me.
The code below I already have, but it doesn't work
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.OleDb;
namespace Eindopdracht
{
public partial class resultaten : Form
{
public resultaten()
{
InitializeComponent();
dataGridView1.Show();
}
private string username;
public void displaydata(String ddata)
{
OleDbConnection conn = new OleDbConnection(#"provider= microsoft.jet.oledb.4.0;data source=C:\\Users\\Jeffrey\\Desktop\\Eindopdracht WOE\\Eindopdracht\\sample.mdb");
string select = "SELECT * FROM prestaties WHERE gebruikerid = '" + label2.Text + "'";
conn.Open();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(select, conn);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.DataSource = ds.tables[0];
conn.Close();
}
public void setUsername(String name)
{
username = name;
label1.Text = username;
setID();
}
public void setID()
{
OleDbConnection vcon = new OleDbConnection(#"provider= microsoft.jet.oledb.4.0;data source=C:\\Users\\Jeffrey\\Desktop\\Eindopdracht WOE\\Eindopdracht\\sample.mdb");
string selectie = "SELECT id FROM inlog WHERE Username='" + label1.Text + "'";
OleDbCommand vcom1 = new OleDbCommand(selectie, vcon);
vcon.Open();
vcom1.ExecuteNonQuery();
OleDbDataReader dr = null;
dr = vcom1.ExecuteReader();
while (dr.Read())
{
var waarde = dr.GetValue(0);
label2.Text = waarde.ToString();
}
I don't know if my code is 100% correct. I've build this by myself. If I use the class displayData in the begin next to InitializeComponent(); I will get an error.

Programmatically acess Google chrome history

I want to index all the user actions and websites in google chrome. i understand that google chrome index all the data in sqlLite database. how can i Programmatically access the chrome web history in my own application
You need to download the appropriate assembly from the SqLite downloads page
Once you add a reference to the SQLite assembly, its very similar to standard ADO.net
All the user history is stored in the History database located at the path in the connection string below
SQLiteConnection conn = new SQLiteConnection
(#"Data Source=C:\Users\YourUserName\AppData\Local\Google\Chrome\User Data\Default\History");
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
// cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;";
// Use the above query to get all the table names
cmd.CommandText = "Select * From urls";
SQLiteDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Console.WriteLine(dr[1].ToString());
}
In Windows form application with Datagridview tool - button click event
private void button1_Click(object sender, EventArgs e)
{
string google = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + #"\Google\Chrome\User Data\Default\History";
string fileName = DateTime.Now.Ticks.ToString();
File.Copy(google, Application.StartupPath + "\\" + fileName);
using (SQLiteConnection con = new SQLiteConnection("DataSource = " + Application.StartupPath + "\\" + fileName + ";Versio=3;New=False;Compress=True;"))
{
con.Open();
//SQLiteDataAdapter da = new SQLiteDataAdapter("select url,title,visit_count,last_visit_time from urls order by last_visit_time desc", con);
SQLiteDataAdapter da = new SQLiteDataAdapter("select * from urls order by last_visit_time desc", con);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
con.Close();
}
try // File already open error is skipped
{
if (File.Exists(Application.StartupPath + "\\" + fileName))
File.Delete(Application.StartupPath + "\\" + fileName);
}
catch (Exception)
{
}
}
Reference source
Here i have copied the History file to Application startup path in order to avoid SQLite error "database is locked".
Used below code getting "Windows/x86_64" as a result
try
{
Class.forName ("org.sqlite.JDBC");
connection = DriverManager.getConnection ("jdbc:sqlite:/C:/Users/tarun.kakkar/AppData/Local/Google/Chrome/User Data/Default/History");
statement = connection.createStatement ();
resultSet = statement.executeQuery ("SELECT * FROM urls");
while (resultSet.next ())
{
System.out.println ("URL [" + resultSet.getString ("url") + "]" + ", visit count [" + resultSet.getString ("visit_count") + "]");
}
}
catch (Exception e)
{
e.printStackTrace ();
}
This piece of code might help you:
//Use sqlite for read chrome history
using System;
using System.IO;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
GetChromehistory();
Console.WriteLine();
}
public void GetChromehistory()
{
//Connection string
string path = #"\Google\Chrome\User Data\Default\History";
string chromehistorypath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + path;
if (File.Exists(chromehistorypath))
{
SQLiteConnection connection = new SQLiteConnection("Data Source=" + chromehistorypath + ";Version=3;New=False;Compress=True;");
connection.Open();
DataSet dataSet = new DataSet();
SQLiteDataAdapter adapter = new SQLiteDataAdapter("select * from urls order by last_visit_time desc", connection);
connection.Close();
adapter.Fill(dataSet);
var allHistoryItems = new List<ChromeHistoryItem>();
if (dataSet != null && dataSet.Tables.Count > 0 & dataSet.Tables[0] != null)
{
DataTable dt = dataSet.Tables[0];
foreach (DataRow historyRow in dt.Rows)
{
ChromeHistoryItem historyItem = new ChromeHistoryItem()
{
URL = Convert.ToString(historyRow["url"]),
Title = Convert.ToString(historyRow["title"])
};
// Chrome stores time elapsed since Jan 1, 1601 (UTC format) in microseconds
long utcMicroSeconds = Convert.ToInt64(historyRow["last_visit_time"]);
// Windows file time UTC is in nanoseconds, so multiplying by 10
DateTime gmtTime = DateTime.FromFileTimeUtc(10 * utcMicroSeconds);
// Converting to local time
DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(gmtTime, TimeZoneInfo.Local);
historyItem.VisitedTime = localTime;
allHistoryItems.Add(historyItem);
}
}
}
}
}
public class ChromeHistoryItem
{
public string URL { get; set; }
public string Title { get; set; }
public DateTime VisitedTime { get; set; }
}

Categories