How to convert Ods file to Data Set C# - c#

I am unable to convert ods file to data set
I have downloaded the file from follwoing link
UK List ods file link
and using following piece of code to convert this ods file to data set
int count = 0;
int list_clear = 1;
string connectionString;
if (ConfigurationManager.AppSettings["OperatingSystem"] == "64Bits")
connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + location + ";Extended Properties=\"Excel 12.0;\"";
else
connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
location + #";Extended Properties=""Excel 8.0;HDR=YES;""";
int recCount = 0;
string xmlData = "";
// Create a factory
DbProviderFactory factory =
DbProviderFactories.GetFactory("System.Data.OleDb");
// Create an adapter
DbDataAdapter adapter = factory.CreateDataAdapter();
// Create a select command to get the dataset
DbCommand selectCommand = factory.CreateCommand();
//selectCommand.CommandText = "SELECT * FROM [sanctionsconlist$]";
selectCommand.CommandText = "SELECT * FROM [sheet1$]";// "SELECT * FROM [Data$]";
// Set up the connection and the connection string
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
selectCommand.Connection = connection;
// Set up the command
adapter.SelectCommand = selectCommand;
// Create the dataset
DataSet ds = new DataSet();
DataSet dsData = new DataSet();
// Load the results
adapter.Fill(ds);
con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStringName"].ConnectionString);
cmd = new SqlCommand();
con.Open();
tran = con.BeginTransaction();
cmd.CommandText = "USP_ImportUKListSanctionListData";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Transaction = tran;
cmd.Parameters.Add("#xmlData", SqlDbType.NVarChar, -1);
cmd.Parameters.Add("#list_clear_flag", SqlDbType.Int);
cmd.Parameters.Add("#update_list", SqlDbType.Int);
cmd.Parameters.Add("#Error", SqlDbType.Int);
DataTable dt = ds.Tables[0].Clone();
but i get the error, external table is not in the expected format
Can any one help me in this reagard, thanks

Related

From the database I am trying to display a single common name using label please guide me I am a beginner in C#

I am trying to make a feedback form where I want to show the name which is inserted n number of times.
My DataBase has for example 9 duplicate names as feedback was input for that same person 9 times and I want to display it on the result that common name.
Please help me out to complete the code/solution or Correct the code and get the result.
SQL QUERY IS RUNNING PROPERLY IT IS SELECTING THE SINGLE DATA FROM DATABASE BUT HOW TO SHOW THIS ON WEBPAGE
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT DISTINCT (F2NAME) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "'";
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
try using below code, i have made some change in sql query to get only single record as result.
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT max(DISTINCT (F2NAME)) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "' AND F2NAME<>'' AND F2NAME IS NOT NULL" ;
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
i have not check but it will work, if you result binding to lable is correct.

How I can manage to fill listview with .dbf

I'm trying to open .dbf via c# wpf and load it into a ListView, but I have no luck.
In my ViewModel:
public void DBF()
{
var databasePath = #"C:\Users\jesson\Desktop\FLCOLU_Building_Outline_Hints_308EL_section3_2180ER_QC.dbf";
var connectionString = string.Format("DSN=dBase Files", databasePath);
OdbcConnection connection = new OdbcConnection(connectionString);
connection.Open();
var _command = connection.CreateCommand();
var query = string.Format(#"SELECT * FROM C:\Users\jesson\Desktop\FLCOLU_Building_Outline_Hints_308EL_section3_2180ER_QC.dbf");
string commandText = query;
var _dataAdapter = new OdbcDataAdapter(commandText, connection);
DataSet _dataSet = new DataSet();
DataTable _dataTable = new DataTable();
_dataSet.Reset();
_dataAdapter.Fill(_dataSet);
_dataTable = _dataSet.Tables[0];
var rows = _dataTable.Rows;
string userName = rows[0].ItemArray[1] as string;
string password = rows[0].ItemArray[2] as string;
UserDataVar = new InputDataSingle
{
UserName = userName,
Password = password
};
connection.Close();
}
Did I do something wrong? Any other ideas?
here you go. try below one.
string filename= //yourfilePath;
string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ filename +";Extended Properties=dBASE IV;User ID=Admin;Password=;";
DataTable dt = new DataTable();
using (OleDbConnection con = new OleDbConnection(constr))
{
var sql = "select * from " + filename ;
OleDbCommand cmd = new OleDbCommand(sql, con);
con.Open();
DataSet ds = new DataSet(); ;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
dt =ds.Tables[0]
}
here how to pass data to listview or dataGrid.;
mylistview.ItemsSource = dt.DefaultView;
Condition
you have to create View to your ListView;

Attempting to connect to Excel spreadsheet in C#

I am trying to pull a bunch of data from a spreadsheet, however I am not able to make a successful connection in my C# code. B
Below is the connection string and the code that I am using to make the connection. The goal of the program is to pull the data from the spreadsheet and deposit it into a SQL database. I cannot get past the connection.open() command, however without receiveing this error message:
"External table is not in the expected format"
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\nearod\Desktop\TestLoad.xlsx;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
string queryString = "SELECT * FROM [SQL AgentUnique ID Test Load$]";
try
{
OleDbDataReader reader;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
counter++;
//Access db values
string compCode = "";
string agId = "";
string fName = "";
string lName = "";
string nameSuffix = "";
compCode = reader.GetValue(0).ToString();
agId = reader.GetString(1);
fName = reader.GetString(2);
lName = reader.GetString(3);
nameSuffix = reader.GetString(4);
sqlComm.Parameters.Add(companyCode);
sqlComm.Parameters.Add(agentID);
sqlComm.Parameters.Add(firstName);
sqlComm.Parameters.Add(lastName);
sqlComm.Parameters.Add(suffix);
//Initialize connection objects
cm = Dts.Connections["QUAHILSQ03"];
sqlConn = (SqlConnection)cm.AcquireConnection(Dts.Transaction);
sqlComm = new SqlCommand("AgentResourcesU01.dbo.sp_AgentIdAprCheck", sqlConn);
sqlComm.CommandType = CommandType.StoredProcedure;
//Execute stored procedure
sqlComm.ExecuteNonQuery();
}
reader.Close();
connection.Close();
OleDbConnection.ReleaseObjectPool();
}
For *.xlsx, you need the Ace drivers: Microsoft.ACE.OLEDB.12.0
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\nearod\Desktop\TestLoad.xlsx;
Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
Wrote this a long while back. It's in WebForms, but the .cs file shows you want you need:
converting an excel spreadsheet to a dataset, datatable and multi-dimensional array
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+FileToConvert+";Extended Properties=Excel 8.0;";
try
{
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
//this next line assumes that the file is in default Excel format with Sheet1 as the first sheet name, adjust accordingly
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connection);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
adapter.Fill(ds);//now you have your dataset ds now filled with the data and ready for manipulation
// do stuff
}

Problem reading excel sheet

SqlDataReader reader;
string r="";
if ((FileUpload1.PostedFile != null)&&(FileUpload1.PostedFile.ContentLength > 0))
{
r = System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName);
}
OleDbConnection oconn =
new OleDbConnection
(#"Provider=Microsoft.Jet.OLEDB.4.0;"
+ #"Data Source="+r+";"
+ #"Extended Properties=""Excel 8.0;HDR=Yes;""");
oconn.Open();
OleDbCommand dbcom = new OleDbCommand("SELECT * FROM [Sheet1$]", oconn);
OleDbDataReader dbreader = dbcom.ExecuteReader();
int rni = dbreader.GetOrdinal ("RollNo");
int mki = dbreader.GetOrdinal ("marks");
Here the program works only if the excel sheet is present in the project folder. And if any changes are made to the excel sheet and then the program is run again, then only the rows that were present before are fetched, and not the ones added later. Please help me.....thanks in advance.....
Hi Please post the complete code, alternatively you can import the complete worksheet to a Datatable object with the below method and retrieve required columns and rows of DataTable
static public DataTable ExecuteOleDataTable(string sql, string oledbconnectionstring)
{
using (OleDbCommand command = new OleDbCommand())
{
command.CommandType = CommandType.Text;
OleDbConnection oledbconnection = new OleDbConnection(oledbconnectionstring);
command.Connection = new OleDbConnection(oledbconnectionstring); ;
command.CommandText = sql;
if (oledbconnection.State == System.Data.ConnectionState.Open)
oledbconnection.Close();
oledbconnection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(command);
DataTable datatable = new DataTable();
sda.Fill(datatable);
oledbconnection.Close();
return datatable;
}
}

Loading Access DB Table to Datatable

I have a database in .ACCDB format with some tables.
I'm successfully loading it into an OleDbDataReader with the following code:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\\marcelo.accdb";
OleDbConnection conn = new OleDbConnection(connectionString);
string sql = "SELECT * FROM Clientes";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
OleDbDataReader reader;
reader = cmd.ExecuteReader();
I'd like to load the table "clientes" to a datatable instead. How should I do it ?
string connString =
"Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\\marcelo.accdb";
DataTable results = new DataTable();
using(OleDbConnection conn = new OleDbConnection(connString))
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Clientes", conn);
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
}

Categories