I would like to ask, why I get this exception when I try to connect excel 2000/3 and also 2010?
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OleDb;
namespace md1_connect
{
class Program
{
static void Main (string[] args)
{
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"Book1.xls\"";
OleDbConnection MyConn = new OleDbConnection(ConnectionString);
OleDbCommand cmd = new OleDbCommand("SELECT * FROM[Sheet2$]", MyConn);
MyConn.Open();
OleDbDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
Console.WriteLine(dataReader.GetDouble(0));
}
MyConn.Close();
}
}
}
You need to tell the provider you're using Excel 97-2003 (xls as opposed to xlsx) by appending:
Extended Properties="Excel 8.0"
E.g.
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"Book1.xls\";Extended Properties=\"Excel 8.0\"";
I dont know what the exception is but I may know what you are talking about. You are probably compiling as x64 bit, please force it to run as 32 bit (x86). I believe that setting can be set in your Project Properties under Build Options
Related
I am exporting a gridview to MS Access but I am facing some problems.
What namespace I should be using while creating a MS access database in C#?
For playing with Microsoft office realated document like MS-Access or MS-Excel you need to add
using System.Data.OleDb
write some code
OleDbConnection conn = new OleDbConnection();
then right click on the class name (e.g. OleDbConnection) and select resolve or you can use shortcut ctrl + .
In this specific case you need to add
using System.Data.OleDb
You need to add reference to this namespace in your project System.Data.OleDb
and then use it on you file like this
using System.Data.OleDb
The System.Data.OleDb namespace needs to be added in your c# file. You can refer the below detailed sample which help you to learn more about MS Access data storage and retrieval through C#.
Link to Refer
I am using 2 namespace
using ADOX;
Using ADODB;
yes i am using namespace
using System.Data.OLEDB; with 2 namespace
using ADOX;
using ADODB; with this code
ADOX.Catalog cat = new ADOX.Catalog();
ADOX.Table table = new ADOX.Table();
//Create the table and it's fields.
table.Name = "Table1";
table.Columns.Append("PartNumber", ADOX.DataTypeEnum.adVarWChar, 6); // text[6]
table.Columns.Append("AnInteger", ADOX.DataTypeEnum.adInteger, 10); // Integer
try
{
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=d:/m2.accdb;" + "Jet OLEDB:Engine Type=5");
cat.Tables.Append(table);
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;" + "Data Source=d:/m2.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Table1([PartNumber],[AnInteger]) VALUES (#FirstName,#LastName)";
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = "neha";
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = 20;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
result = false;
}
cat = null;
I am working on writing a simple program to import an excel sheet into my database but I am running into an error of:
Could not find installable ISAM
I am not sure what this means and after hours of searching with so many different topics I have turned to SO. There is a lot of talk of Jet and ACE where I am not sure what the difference is but here is the rundown: I have an excel file called test or test1 and I just want to import the first sheet in the file. here is my source code so far:
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;
using System.Data.Common;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
string filePath = null;
public Form1()
{
InitializeComponent();
}
//Method to check database connection
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "Data Source=Zach-PC;Initial Catalog=master;Integrated Security=SSPI;";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
//Method to select a file
private void button2_Click(object sender, EventArgs e)
{
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Zach/Documents/test1.xls;Extended Properties=Excel 12.0,HDR=Yes;IMEX=1";
// Create Connection to Excel Workbook
using (OleDbConnection connection =
new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand
("Select * FROM [Sheet1$]", connection);
connection.Open(); //HERE IS WHERE THE ERROR IS
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=Zach-PC;Initial Catalog=master;Integrated Security=True";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "Table";
bulkCopy.WriteToServer(dr);
MessageBox.Show("Data Exoprted To Sql Server Succefully");
}
}
}
}
}
}
Am I approaching this in the right manor?
You need to wrap Extended Properties part of the connection string in the quotation marks:
// here and here
// --> v v
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Zach/Documents/test1.xls;Extended Properties=""Excel 12.0,HDR=Yes;IMEX=1""";
The Office oledb driver is probably not installed on your computer. You should download it from microsoft website. After the installation, your code should run.
If you are reading office 2007 (or newer) excel files then I will suggest to use Open source library Epplus to read the excel file.It is purely .NET library and you wont be dependent on oledb driver.
epplus
EPPlus is a .net library that reads and writes Excel 2007/2010 files using the Open Office Xml format (xlsx).
you can easily read an excel file into datatable using this library. have a look at this thread
How convert stream excel file to datatable C#?
When I try to write in C# a connection to my app to my database, I build the application successfully in Visual Studio 2005 but when I run the site in debugger i get an error:
Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 118.
Here is the connection code that is giving the error:
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Server"].ConnectionString);
I have the connection string written correctly in my web.config, file so im clueless on what this remotely means. Im not sure if im missing anything. Any help appreciated. Here is my entire code for the section that might help:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Data.SqlClient;
public partial class RateAnalyzerPage: System.Web.UI.Page
{
protected void Search_Click(object sender, EventArgs e)
{
string IDnumber = mechantNumber.Text;
string selectSQL = "SELECT FROM Authors Where MID='"+ IDnumber +"'";
// SqlConnection con = new SqlConnection(#"Server=");
//SqlConnection con = new SqlConnection();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Server"].ConnectionString);
SqlDataReader reader;
try
{
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL, con);
reader = cmd.ExecuteReader();
while (reader.Read())
{
QualVol.Text = reader["TotalVolume"].ToString();
}
reader.Close();
}
catch (Exception err)
{
}
finally
{
con.Close();
}
}
}
Let me know if im missing some data that would help.
Heres the connection string:
I've separated out and XML decoded the connection string value:
Data Source=Server;Initial Catalog=Odata;Integrated Security=True;MultipleActiveResultSets=False;Packet Size=4096;Application Name="Microsoft SQL Server Management Studio"User ID=Name;Password=PW
As you can see, you're missing a ; between Application Name and User ID. I'm not sure if that's the issue, but it's possible.
Your connection string use the Integrated Security=True, but the right syntax is
Integrated Security=SSPI; or Trusted_Connection=True so change it and remove the UserId and Password.
(or remove Integrated Security=True and leave UserID and Password)
Try to change something in your code.
protected void Search_Click(object sender, EventArgs e)
{
string IDnumber = mechantNumber.Text;
string selectSQL = "SELECT * FROM Authors Where MID=#num";
using(SqlConnection con = new SqlConnection
(System.Configuration.ConfigurationManager.ConnectionStrings
["Server"].ConnectionString))
{
SqlDataReader reader;
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("#num", IDNumber);
reader = cmd.ExecuteReader();
while (reader.Read())
{
QualVol.Text = reader["TotalVolume"].ToString();
}
reader.Close();
}
}
Try to use the using statemend, this guarantees the disposing of your connection
Try to use parametrized query, this avoid Sql Injection attacks and quoting problems
Also SELECT requires a fields list or *
I think Jacob has it right. On a side note, don't do this:
string selectSQL = "SELECT FROM Authors Where MID='"+ IDnumber +"'";
This will lead to sql injection attacks, just like the one that was used to get yahoo user accounts last week.
Do this instead:
string selectSQL = "SELECT * FROM Authors Where MID=#ID";
cmd.Parameters.AddWithValue("#ID", IDnumber );
I'm new to C#, creating excel plugins and also new to ExcelDNA. I got the examples working on http://exceldna.codeplex.com/wikipage?title=Getting%20Started. The UDF "MultiplyThem" works as expected.
When I modify example #3 on that site to grab data from a mysql database. I reference not only ExcelDna.Integration.dll but also MySql.Data.dll in my project. I then compile it with this statement:
c:\windows\microsoft.net\framework\v2.0.50727\csc.exe /target:library /reference:ExcelDna.Integration.dll /reference:MySql.Data.dll TestLib.cs
When I open up the excel-add in and start typing in my UDF(in this case, "=MultiplyThem()") there is no UDF called "MultiplyThem". Why did it suddenly stop working? Here's my C# code:
using ExcelDna.Integration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
public class MyFunctions
{
[ExcelFunction(Description = "Grabs data from database", Category = "Useful functions")]
public static string MultiplyThem(string[] args)
{
string connString = "Server=localhost;Port=3306;Database=test;Uid=root;password=pword";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT field_value FROM customers";
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
string myvariable = "bad";
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
myvariable = reader["field_value"].ToString();
}
return myvariable;
}
}
And my Test1.dna file (I am targeting .NET Framework 4 in my project):
<DnaLibrary RuntimeVersion="v4.0">
<ExternalLibrary Path="TestLib.dll"/>
</DnaLibrary>
Excel-DNA does not currently support string arrays as parameters. If you change the string[] args to object[] args it should be fine.
I am trying to write t-sql in C# (visual studio). I have this code to connect to the database:
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;
using Microsoft.SqlServer.Server;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Xtreme\\Desktop\\CardsDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
Where/how do I write the T-SQL code and how do I get the result?
Can someone give me an simple select example in my code?
You can use DataAdapter.Fill Method:
try
{
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM Employee", cnn))
{
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// Render data onto the screen
dataGridView1.DataSource = t; //if you want.
}
}
catch (Exception ex)
{
MessageBox.Show("Problem!");
}
Create a SqlCommand and set the CommandType to CommandType.Text. Then add your SQL to the CommandText property of the SqlCommand.
SqlCommand command = new SqlCommand(commandName, (SqlConnection)Connection);
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM MyTable";
IDataReader result = command.ExecuteReader();
Ardman already showed you how to execute any arbitary sql command. But what i didn't answer very well, is where to put your sql statement.
I think it is a very bad behaviour and also not very good to read if you put your statement directly into the code.
A better method (in my eyes) is the following:
Within your project create a new folder (maybe called Queries)
Right click this folder and select Add - New Item
In the dialog just select Textfile and give it the name about what this query will do
Make sure you replace the file extension from .txt to .sql
Just put your statement right into this file
In the Resource Editor add this file as a resource
Now you can access this sql statement within your project just by using Properties.Resources.MySqlStatement