I have loaded Two Excel files in two datable now i have to check that the Specific value of column one of DataTable1 exist in specific cloumn of DataTable 2 or not. I have only one output in rich Text Box which is wrong . What should i do
string connectionStringold = Application.StartupPath + "\Language-Resources-3.0" + ".xls";
string connstrold = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + connectionStringold + ";Extended Properties=Excel 8.0";
OleDbConnection connold = new OleDbConnection(connstrold);
string strSQLold = "SELECT * FROM [Resources$]";
OleDbCommand cmdold = new OleDbCommand(strSQLold, connold);
OleDbDataAdapter daold = new OleDbDataAdapter(cmdold);
DataTable dtold = new DataTable();
daold.Fill(dtold);
// dataGridView1.DataSource = dtold;
string connectionString = Application.StartupPath + "\\x_Lang_Res" + ".xls";
string connstr = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + connectionString + ";Extended Properties=Excel 8.0";
OleDbConnection conn = new OleDbConnection(connstr);
string strSQL = "SELECT * FROM [Chinese$]";
OleDbCommand cmd = new OleDbCommand(strSQL, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
// dataGridView1.DataSource = dt;
foreach (DataRow row in dt.Rows)
{
string aa = row[1].ToString();
foreach (DataRow rowold in dtold.Rows)
{
string old = rowold[3].ToString();
if (!rowold[3].ToString().Contains(aa))
{
richTextBox1.Text = aa + "\n\r";
}
}
}
You are setting the result to the RTB.Text property each time.
if (!rowold[3].ToString().Contains(aa))
{
richTextBox1.Text = aa + "\n\r";
}
You need to use += to append it.
if (!rowold[3].ToString().Contains(aa))
{
richTextBox1.Text += aa + "\n\r";
}
or even better use
RTB.AppendText( string.Format( "....." , a , b );
Try Replacing this part of the code
if (!rowold[3].ToString().Contains(aa))
{
richTextBox1.Text = aa + "\n\r";
}
With this
if (aa!=old)
{
richTextBox1.Text = richTextBox1.Text + aa + "\n\r";
}
Related
How to get many times are matched from keywords for each matched record from csv files.
That I need to search all the characters in the [StringData] in the csv file to find out the records which contain the words and many times that are matched in the StringData on the Text box Search.
Code
string search = txtBoxSearch.Text;
string pathOnly = Path.GetDirectoryName(csvPath);
string fileName = Path.GetFileName(csvPath);
string sql = #"SELECT F1 AS StringID, F2 AS StringContent FROM [" + fileName + "] WHERE F2 LIKE '%" + search + "%'";
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=No\""))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
GridViewResult.DataSource = dataTable;
GridViewResult.DataBind();
}
You can add a new column to DataTable and calculate it's value on memory foreach rows by using Regex.Matches:
string search = txtBoxSearch.Text;
string pathOnly = Path.GetDirectoryName(csvPath);
string fileName = Path.GetFileName(csvPath);
string sql = #"SELECT F1 AS StringID, F2 AS StringContent FROM [" + fileName + "] WHERE F2 LIKE '%" + search + "%'";
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=No\""))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
dataTable.Columns.Add("MatchTimes", typeof(System.Int32));
foreach(DataRow row in dataTable.Rows)
{
row["MatchTimes"] = Regex.Matches(row["StringContent"].ToString(), row["StringID"].ToString()).Count
}
GridViewResult.DataSource = dataTable;
GridViewResult.DataBind();
}
See also: Count the number of times a string appears within a string
I want to view the Excel data with headers inside datagridview.
I have tried changing HDR=Yes to HDR=No. It shows all the data but I have headers on the Excel file.
I changed this code:
string pathconn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\";";
To:
string pathconn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\";";
This is my Excel data:
You have to put in the column name the text of the first row of the datatable.
Then delete the row.
Datatable dtExcel = importaExcelaDT(filePath);
for(int i = 0; i < dtExcel.Columns.Count; i++)
{
string columnName = dtExcel.Rows[0][i].ToString();
if (columnName == "") //throws error if column name is empty
columnName = " ";
dtExcel.Columns[i].ColumnName = columnName;
}
dtExcel.Rows.RemoveAt(0);
yourDataGridView.DataSource = dtExcel;
I get data with headers with this function.
public DataTable importaExcelaDT(string file)
{
DataTable dt = new DataTable();
DataTable dtExcel = new DataTable();
OleDbCommand cmdExcel = new OleDbCommand();
string cadenaConexion = "provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + file + "';Extended Properties = \"Excel 12.0 Xml;HDR=No;IMEX=1\";";
OleDbConnection olConexion = new OleDbConnection(cadenaConexion);
olConexion.Open();
OleDbDataAdapter oda = new OleDbDataAdapter();
dt = olConexion.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string sheet = dt.Rows[0]["TABLE_NAME"].ToString();
cmdExcel.Connection = olConexion;
cmdExcel.CommandText = "SELECT * FROM [" + sheet + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dtExcel);
olConexion.Close();
olConexion.Dispose();
oda.Dispose();
return dtExcel;
}
can somebody tell me why this update procedure doesn't work? I want to read data to dataset from XLS and it works just fine but UPDATE doesn't work at all. No errors, no changes, like it doesn't exist. The file creates but values are just a copy from original xls.
Xls sheet format is pretty simple, one column: id 1 2 3
string string_conn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path\name.xls;Extended Properties='Excel 8.0;HDR=Yes;'";
OleDbConnection conn = new OleDbConnection(string_conn);
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
comboBox1.DataSource = excelSheets;
string xlsSheet = comboBox1.SelectedItem.ToString();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + xlsSheet + "]", conn);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
adapter.UpdateCommand = new OleDbCommand ("UPDATE " + xlsSheet + " SET id = " + tbox1.Text + " WHERE id = " + tbox2.Text + "", conn);
adapter.UpdateCommand.Parameters.Add("#id", OleDbType.Char, 255).SourceColumn = "id";
adapter.UpdateCommand.Parameters.Add("#Oldid", OleDbType.Char, 255, "id").SourceVersion = DataRowVersion.Original;
adapter.Update(dataset);
dataset.AcceptChanges();
DataTable dtable = new DataTable();
dtable = dataset.Tables[0];
StringBuilder str = new StringBuilder();
foreach (DataRow dr in dtable.Rows)
{
foreach (var field in dr.ItemArray)
{
str.Append(field.ToString());
str.Append(", ");
}
str.Replace(",", str.AppendLine().ToString(), str.Length - 1, 1);
}
MessageBox.Show(str.ToString()); //for test's sake
string pathFile = #"path\filename.csv";
if (!File.Exists(pathFile))
{
File.Create(pathFile).Close();
}
File.AppendAllText(pathFile, str.ToString());
Something is wrong with parameters probably but I tried this way and also no go (I added 2nd column so id stays the same just to find proper row), I get UPDATE command syntax error on execute:
string string_conn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path\arkusz.xls;Extended Properties='Excel 8.0;HDR=Yes;'";
OleDbConnection conn= new OleDbConnection(string_conn);
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
comboBox1.DataSource = excelSheets;
string xlsSheet = comboBox1.SelectedItem.ToString();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + xlsSheet + "]", conn);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
adapter.UpdateCommand = new OleDbCommand("UPDATE " + xlsSheet + " SET nazwa = #nazwa WHERE id = #id", conn);
adapter.UpdateCommand.Parameters.AddWithValue("#id", tbox1.Text).OleDbType = OleDbType.Integer;
adapter.UpdateCommand.Parameters.AddWithValue("#nazwa", tbox2.Text).OleDbType = OleDbType.VarChar;
adapter.UpdateCommand.ExecuteNonQuery();
adapter.Update(dataset);
dataset.AcceptChanges();
DataTable dtable = new DataTable();
dtable = dataset.Tables[0];
StringBuilder str = new StringBuilder();
foreach (DataRow dr in dtable.Rows)
{
foreach (var field in dr.ItemArray)
{
str.Append(field.ToString());
str.Append(", ");
}
str.Replace(",", str.AppendLine().ToString(), str.Length - 1, 1);
}
MessageBox.Show(str.ToString());
string sciezkaPlik = #"path\filename.csv";
if (!File.Exists(sciezkaPlik))
{
File.Create(sciezkaPlik).Close();
}
File.AppendAllText(sciezkaPlik, str.ToString());
I solved the issue. For future reference it works well like this:
string string_conn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path\arkusz.xls;Extended Properties='Excel 8.0;HDR=Yes;'";
OleDbConnection conn = new OleDbConnection(string_conn);
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
comboBox1.DataSource = excelSheets;
string xlsSheet = comboBox1.SelectedItem.ToString();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + xlsSheet + "]", conn);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
OleDbCommand odbc = new OleDbCommand("UPDATE ["+xlsSheet+"] SET nazwa = " + txtNewValue.Text + " WHERE id = " + txtID.Text + "", conn);
adapter.UpdateCommand = odbc;
odbc.Parameters.AddWithValue("nazwa", txtNewValue.Text).OleDbType = OleDbType.VarChar;
odbc.Parameters.AddWithValue("id", txtID.Text).OleDbType = OleDbType.Integer;
odbc.ExecuteNonQuery();
dataset.Clear();
adapter.Fill(dataset);
DataTable dtable = new DataTable();
dtable = dataset.Tables[0];
StringBuilder str = new StringBuilder();
foreach (DataRow dr in dtable.Rows)
{
foreach (var field in dr.ItemArray) /
{
str.Append(field.ToString());
str.Append(", ");
}
str = str.Replace(',', '\n');
}
string filePath= #"path\filename.csv";
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
File.WriteAllText(filePath, str.ToString());
EDIT - I think it may be that this line needs to have the parameters put in as a question mark instead of having the actual values passed in, so more like this:
adapter.UpdateCommand = new OleDbCommand ("UPDATE " + xlsSheet + " SET id = ? WHERE id = ?", conn);
Then your next couple of lines are correct, they are clever enough to replace the question marks from the UpdateCommand with the actual values at run time:
adapter.UpdateCommand.Parameters.Add("#id", OleDbType.Char, 255).SourceColumn = "id";
adapter.UpdateCommand.Parameters.Add("#Oldid", OleDbType.Char, 255, "id").SourceVersion = DataRowVersion.Original;
Hare is a very simple method to do an insert into an Excel sheet.
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());
}
}
}
}
I'm converting .csv file to datatable like below.
string header = isFirstRowHeader ? "Yes" : "No";
string itinerarycsvfilePath = Path.GetDirectoryName(#"D:\projects\MSC cruise\MSCCruiseProjects\MsccruiseWithLogin\MsccruiseWithLogin\UnzippedFiles\itinff_gbr_eng.csv");
string filename = Path.GetFileName(#"D:\projects\MSC cruise\MSCCruiseProjects\MsccruiseWithLogin\MsccruiseWithLogin\UnzippedFiles\itinff_gbr_eng.csv");
string sql = #"SELECT * FROM [" + filename + "]";
using (OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + itinerarycsvfilePath +
";Extended Properties=\"Text;HDR=" + header + "\""))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable("ItineraryDetails");
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
then the result when I look with quick watch
Am I doing something wrong.I feel like that because table does not show like columns.
what can I do for that.
hope your help.
See code below
public class CSVReader
{
public DataSet ReadCSVFile(string fullPath, bool headerRow)
{
string path = fullPath.Substring(0, fullPath.LastIndexOf("\\") + 1);
string filename = fullPath.Substring(fullPath.LastIndexOf("\\") + 1);
DataSet ds = new DataSet();
try
{
if (File.Exists(fullPath))
{
string ConStr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}" + ";Extended Properties=\"Text;HDR={1};FMT=Delimited\\\"", path, headerRow ? "Yes" : "No");
string SQL = string.Format("SELECT * FROM {0}", filename);
OleDbDataAdapter adapter = new OleDbDataAdapter(SQL, ConStr);
adapter.Fill(ds, "TextFile");
ds.Tables[0].TableName = "Table1";
}
foreach (DataColumn col in ds.Tables["Table1"].Columns)
{
col.ColumnName = col.ColumnName.Replace(" ", "_");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return ds;
}
}
I am importing data from MS Excel.
The code i have written is,
var ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
uploadfile.PostedFile.FileName + ";" + "Extended Properties=Excel 12.0;";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
try
{
var objCmdSelect = new OleDbCommand("select * from [Sheet1$]", objConn);
}
and so on.
I got an error which looks very generic to me
The Microsoft Office Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly
*
My worksheet name is spelled correclty
but for my confirmation, i did below code
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if(dt == null)
{
return null;
}
var excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
*
but i got my Data Table null.
My question is the connection is open successfully but i can't read data from the excel file.
Is there any special Authentication required.?
because i am getting the above error.
Instead if Ace.OLEDB you may try by Microsoft.Jet.OLEDB, because I faced the simillar then I switch over to Jet.OLEDB
string MyExelFile = "C:\Temp\Sample.xls";
string MyExcelSheet = "[Sheet1$]";
string StrConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + MyExelFile + ";
Extended Properties=\"Excel 8.0; HDR=Yes; IMEX=1\"";
String MySQLSelect = "select * from " + MyExcelSheet + "";
DataTable Items=new DataTable() ;
System.Data.OleDb.OleDbConnection Cn = new System.Data.OleDb.OleDbConnection();
Cn.ConnectionString = StrConn;
System.Data.OleDb.OleDbDataAdapter Da = new System.Data.OleDb.OleDbDataAdapter
(MySQLSelect, Cn);
Cn.Open();
Da.Fill(Items);
Cn.Close();
</pre>