I have a application to read a excel cell value which is in scientific notation.
I have tried the below code :
decimal dec = Decimal.Parse("1.01703E+11", System.Globalization.NumberStyles.Any);
Result : 101703000000M
But the excel value is different from the result
This is the correct excel value "101703000026"
Connection method
public DataSet ReadExcelData(string Path)
{
OleDbConnection oledbConn = null;
try
{
// need to pass relative path after deploying on server
string path = System.IO.Path.GetFullPath(#Path);
oledbConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
oledbConn.Open();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter oleda = new OleDbDataAdapter();
DataSet ds = new DataSet();
// selecting distict list of Slno
cmd.Connection = oledbConn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [DailySalesReport$]";
oleda = new OleDbDataAdapter(cmd);
oleda.Fill(ds);
// binding form data with grid view
return ds;
}
// need to catch possible exceptions
catch
{
return null;
}
finally
{
oledbConn.Close();
}
}
How can I get the correct value. Please advice.
This is my output
Related
I need some help displaying values of excel in datagridview.
i manage to display values but some of the values are missing(columns,and values of rows).i have 1000 rows in my excel file and the data grid view is only displaying 333 items in it. and i have 148 number of columns but it only display some of it. can someone tell me what the problem is.
here is my code:
public partial class MainBagsakan : Form
[enter image description here][1]
String WOmain=#"C:\Users\tjjtabije\Desktop\TestExcelUpdater\TestUnoREFARM.xlsx";
private string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\t-jjtabije\\Desktop\\TestExcelUpdater\\TestUnoREFARM.xlsx;Extended Properties='Excel 12.0 Xml;IMEX=1;HDR=YES;TypeGuessRows=0;ImportMixedTypes=Text'";
private void WorkOrderTab()
{
string filePath = Path.GetFullPath(WOmain);
string extension = Path.GetExtension(filePath);
string conStr, sheetName;
conStr = string.Empty;
//Get the name of the First Sheet.
using (OleDbConnection con = new OleDbConnection(Excel07ConString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
con.Close();
}
}
using (OleDbConnection con = new OleDbConnection(Excel07ConString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
cmd.Connection = con;
cmd.CommandText = "SELECT * [" +sheetName+ "]";
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
//Populate DataGridView.
WorkLoadDisp.DataSource = dt;
label1.Text = dt.Rows.Count.ToString();
}
}
}
}
It is unnecessary to open and close the connection twice as you are with the two separate using clauses. The first one simply gets the name of a worksheet sort of, as a named range could also be returned. I simply put all the code into a single group and it seems to work as expected.
Added a missing FROM to the select statement:
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
The changes I made are below...
using (OleDbConnection con = new OleDbConnection(Excel07ConString)) {
using (OleDbCommand cmd = new OleDbCommand()) {
using (OleDbDataAdapter oda = new OleDbDataAdapter()) {
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
DataTable dt = new DataTable();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
//con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
//Populate DataGridView.
WorkLoadDisp.DataSource = dt;
label1.Text = dt.Rows.Count.ToString();
}
}
}
Hope this helps.
I am writing a a C# application, and I am stuck at searching the database and populating a data grid view. However I want to use this with command builder.
The issue is, I need the search to work across all columns in the database. I thought using OR and LIKE statements would do this. But instead I get either invalid syntax or no column name exists in the search.
Does anyone know a solution?
My current .cs:
private void btnSearchJob_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = (#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MTR_Database;Integrated Security=True");
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE " +txtSearchJob.Text+ " OR [Manufacturer] LIKE " +txtSearchJob.Text+ ")";
// DataAdapter
myDA = new SqlDataAdapter(selectQuery, con);
// SqlCommand
SqlCommand myCMD = new SqlCommand(selectQuery, con);
// DataAdapter to Command
myDA.SelectCommand = myCMD;
// Define Datatable
myDT = new DataTable();
// Command Builder (IS GOD!)
SqlCommandBuilder cb = new SqlCommandBuilder(myDA);
// Teach Command builder to be a boss!
myDA.UpdateCommand = cb.GetUpdateCommand();
myDA.InsertCommand = cb.GetInsertCommand();
myDA.DeleteCommand = cb.GetDeleteCommand();
// Fill the DataTable with DataAdapter information
myDA.Fill(myDT);
// Fill DataTable with Database Schema
myDA.FillSchema(myDT, SchemaType.Source);
// Bind The Data Table to the DataGrid
dataGridView1.DataSource = myDT;
// AutoSize Datagrid Rows and Colums to fit the Datagrid
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
}
// Catch Exception
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "SQL ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
NOTE:
I am aware of using parameters, I am simply using this to see if it will work when I will add parameters later.
this is what I use to get everything back into a DataTable
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(List<SqlParameter> sqlParameters, string connStr, string storedProcName)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = storedProcName;
sqlCmd.CommandTimeout = 5000;
foreach (var sqlParam in sqlParameters)
{
sqlCmd.Parameters.Add(sqlParam);
}
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
sqlParameters.Clear();
return dt;
}
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(string connStr, string query)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = query;
sqlCmd.CommandTimeout = 5000;
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
return dt;
}
hopefully this is pretty self explanatory to you, however pass in a list of SQL Parameters, connection string, and the stored procedure name, or use the second one where you pass in the inline SQL and the connection string.
I think you are missing ' in the query. Try this...
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE '" +txtSearchJob.Text+ "' OR [Manufacturer] LIKE '" +txtSearchJob.Text+ "')";
When import Microsoft Excel file to C# (WPF), specific characters in Column Names (Column Headers) will be replaced.
eg ! it becomes _, and . to #. How to stop it?
connectionString:
Provider=Microsoft.ACE.OLEDB.12.0; Data Source="+filePath+";Extended Properties="Excel 8.0;HDR=YES;CharacterSet=65001;";
And method:
public DataSet ImportExcel(string fileName)
{
tableList = null;
DataSet ds = new DataSet();
string connectionString = GetConnectionString(fileName);
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
// Get all Sheets in Excel File
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
tableList = new string[dtSheet.Rows.Count];
// Loop through all Sheets to get data
foreach (DataRow dr in dtSheet.Rows)
{
string sheetName = dr["TABLE_NAME"].ToString();
tableList[dtSheet.Rows.IndexOf(dr)] = sheetName;
Console.WriteLine("TABLE_NAME: " + sheetName);
if (!sheetName.EndsWith("$"))
continue;
// Get all rows from the Sheet
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
DataTable dt = new DataTable();
dt.TableName = sheetName;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
rowsCount += dt.Rows.Count;
ds.Tables.Add(dt);
}
cmd = null;
conn.Close();
}
return ds;
}
Basically you are limited to what characters are allowed in column names, these are letters, numbers and characters: ##$_ see here. The $ symbol and numbers aren't allowed to be the first character either.
I am importing excel files to my application and sometimes worksheets column names have "$" sign in it. I receive this Exception:
System.Data.OleDb.OleDbException was unhandled
Message=''6um$'$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long.
In this sheet "6um$" is a column name.
This is my code:
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
OleDbDataAdapter cmd = new System.Data.OleDb.OleDbDataAdapter(
"select * from [" + worksheetName + "$]", con);
con.Open();
System.Data.DataSet excelDataSet = new DataSet();
cmd.Fill(excelDataSet);
con.Close();
Any ideas how to handle this situation?
Edit:
I thought the problem was having $ in column name. But turns out, The problem is having $ sign in worksheet name!
Ok, I figured out the solution:
For some reason, the worksheets that I renamed myself have extra $ sign (no idea why, there is no $ sign in the excel but OLEDB returns them with extra $ something like this '6um$'$'). I trim the first $ off and use this code to check is there is any extra $ sign still left:
char delimiterChars = '$';
string[] words = worksheetName.Split(delimiterChars);
worksheetName=words[0];
if (Directory.Exists(serverPath))
{
string FileExist = sp + "book1.xlsx"; ;
string Exten = Path.GetExtension(FileExist);
string g = "sheet1";
if (File.Exists(FileExist))
{
if (Exten == ".xlsx")
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileExist + ";Extended Properties=Excel 12.0";
OleDbConnection oledbConn = new OleDbConnection(connString);
try
{
// Open connection
oledbConn.Open();
string query = String.Format("select * from [{0}$]", g);
// Create OleDbCommand object and select data from worksheet Sheet1
OleDbCommand cmd = new OleDbCommand(query, oledbConn);
// Create new OleDbDataAdapter
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
// Create a DataSet which will hold the data extracted from the worksheet.
DataSet ds = new DataSet();
// Fill the DataSet from the data extracted from the worksheet.
oleda.Fill(ds, "sheetdt");
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
catch (Exception ex)
{
LblSuccess.Text = ex.Message;
}
finally
{
// Close connection
oledbConn.Close();
}
}
}
}
I am having a problem with datetime format in a dataset.
In the database date format is:10/5/2009 10:10:10
but i get an error:FormatException, when attempting to fill the DataSet:
string query = "SELECT * FROM teklif";
c.db = new SQLiteDataAdapter(query, c.con);
c.db.Fill(ds); // Error Here...
dt = ds.Tables[0];
How do I resolve this issue?
It would appear that you are not initializing the adapter right.
MySQLiteConn = new SQLiteConnection("Data Source=" + fileName +
"; Compress = TRUE;");
SQLiteCommand cmd = MySQLiteConn.CreateCommand();
SQLiteDataAdapter dr = new SQLiteDataAdapter(cmd);
SQLiteDataAdapter adapter;
try
{
cmd.CommandText = "SELECT * FROM teklif";
adapter = new SQLiteDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
}
catch (Exception ex)
{
Console.WriteLine("Retrieval of Table Failed. " + ex.Message);
return -1;
}
If that fails then make sure that is the correct table name in your sqlite database.