Attempting to connect to Excel spreadsheet in C# - 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
}

Related

How to convert Ods file to Data Set 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

Updating excel values in data grid view on certain condition

I need to fetch a row value from an excel sheet in data grid view in winform.
I’m able to display the entire excel sheet in the datagridview. But, I need to display particular rows in the grid based on a current date condition.
public DataTable ReadExcel2(string fileName, string fileExt)
{
string connectionstring ;
DataTable dtexcel2 = new DataTable();
connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";
OleDbConnection connection = new OleDbConnection(connectionstring);
OleDbCommand oconn = new OleDbCommand("Select * From [POSFailures$] WHERE Date=#date");
oconn.Connection = connection;
try
{
oconn.Parameters.AddWithValue("#date", DateTime.Now.ToString("MM/dd/yyyy"));
connection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
sda.Fill(dtexcel2);
connection.Close();
}
catch (Exception)
{
}
return dtexcel2;
}
Thanking you in advance
What seems to be happening here is that the Date parameter is not being honored, as you are getting back all of the rows. So, I used Google to figure out how to properly add parameters when using OleDbConnection. I found this:
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement
Source: https://learn.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbcommand.parameters?redirectedfrom=MSDN&view=netframework-4.8#System_Data_OleDb_OleDbCommand_Parameters
Using the example on that page, try changing your code to this:
string connectionstring;
DataTable dtexcel2 = new DataTable();
connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";
OleDbConnection connection = new OleDbConnection(connectionstring);
OleDbCommand command = new OleDbCommand("Select * From [POSFailures$] WHERE Date = ?");
command.Parameters.Add(new OleDbParameter(DateTime.Now.ToString("MM/dd/yyyy"), OleDbType.Date));
command.Connection = connection;
try
{
connection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(command);
sda.Fill(dtexcel2);
connection.Close();
}
catch (Exception)
{
}
Please note that i've not tested this, so I can't promise it will work. But, the main point is... the answer is out there! You just need to go looking for it.

C# Import Excel Data to SQL Table

I am trying to use a method I pulled off of CodePlex, which exports data from Excel into a SQL table. I have made some minor code adjustments, but I still can't seem to get the data to import. Does anyone see anything glaringly wrong with my syntax? Thanks.
static void Main(string[] args)
{
importdatafromexcel("C:/Users/usname/Desktop/TestDirectories/FileSystemWatcher/Test_123.xlsx");
}
public static void importdatafromexcel(string excelfilepath)
{
//declare variables - edit these based on your particular situation
string ssqltable = "Name";
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have different
string myexceldataquery = "select Name,EmployeeID from [sheet1$]";
try
{
//create our connection strings
string sexcelconnectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + excelfilepath + ";Extended Properties=" + "\"excel 8.0;hdr=yes;\"";
//MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelfilepath + ";Extended Properties=Excel 8.0;HDR=YES'");
string ssqlconnectionstring = "server=DESKTOP-6CIMC97;Initial Catalog=TestDB;integrated security=true;connection reset = false";
//<add name="ProductContext" connectionString="Server=DESKTOP-6CIMC97; Initial Catalog=ProductApps; Integrated Security=True" providerName="System.Data.SqlClient" />
//execute a query to erase any previous data from our destination table
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlcmd.Connection.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.WriteToServer(dr);
//while (dr.Read())
//{
// bulkcopy.WriteToServer(dr);
//}
oledbconn.Close();
}
catch (Exception ex)
{
//handle exception
}
}
The problem is here:
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
The while (dr.Read()) block is useful if you are iterating over the results one-by-one.
But it's not you who is iterating over the results. You want the bulk copy operation to do the iterating.
Simply replace it with
bulkcopy.WriteToServer(dr);
This should work for you.
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{
string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
For more info, see the links below.
https://www.codeproject.com/tips/636719/import-ms-excel-data-to-sql-server-table-using-csh
http://www.c-sharpcorner.com/UploadFile/0c1bb2/inserting-excel-file-records-into-sql-server-database-using/
As you can tell, there are MANY ways to do what you want to do.

Import data from an Excel sheet into a SQL Server database

How to import the data from an Excel sheet into SQL Server database in asp net?
Dim OleDbcon As New OleDbConnection((Convert.ToString("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=") & path) + ";Extended Properties=Excel 12.0;")
Dim cmd As New OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon)
Dim objAdapter1 As New OleDbDataAdapter(cmd)
OleDbcon.Open()
Dim dr As DbDataReader = cmd.ExecuteReader()
Dim con_str As String = "Data Source=.;Initial Catalog=studentdetails;Integrated Security=True"
' Bulk Copy to SQL Server
Dim bulkInsert As New SqlBulkCopy(con_str)
bulkInsert.DestinationTableName = "Table name"
bulkInsert.WriteToServer(dr)
OleDbcon.Close()e here
Break this down into two steps:
1) Save the file somewhere - it's very common to see this:
string saveFolder = #"C:\temp\uploads"; //Pick a folder on your machine to store the uploaded files
string filePath = Path.Combine(saveFolder, FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
Now you have your file locally and the real work can be done.
2) Get the data from the file. Your code should work as is but you can simply write your connection string this way:
string excelConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 12.0";", filePath);
You can then think about deleting the file you've just uploaded and imported.
To provide a more concrete example, we can refactor your code into two methods:
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{
string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
You could simply then call SaveFileToDatabase(GetLocalFilePath(#"C:\temp\uploads", FileUpload1));
Consider reviewing the other Extended Properties for your Excel connection string. They come in useful!
Other improvements you might want to make include putting your Sql Database connection string into config, and adding proper exception handling. Please consider this example for demonstration only!
we will create a method data table in which we will take excel sheet info in data table or data set after that we will push that data into SQL database table using SQL bulk
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data
Source=SANI2711\SQLEXPRESS;Initial Catalog=customer;Integrated
Security=True;");
con.Open();
DataTable dt = new DataTable();
dt = DataExcel();
if (dt.Rows.Count > 0)
{
for()
}
}
catch(Exception ex)
{
Response.Write(ex);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data
Source=SANI2711\SQLEXPRESS;Initial Catalog=customer;Integrated
Security=True;");
con.Open();
DataTable dt = new DataTable();
dt = DataExcel();
if (dt.Rows.Count > 0)
{
SqlBulkCopy objbulk = new SqlBulkCopy(con);
objbulk.DestinationTableName = "customer1";
objbulk.ColumnMappings.Add("CustomerID", "CustomerID");
objbulk.ColumnMappings.Add("City", "City");
objbulk.ColumnMappings.Add("Country", "Country");
objbulk.ColumnMappings.Add("PostalCode", "PostalCode");
objbulk.WriteToServer(dt);
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
protected DataTable DataExcel()
{
DataTable dt = new System.Data.DataTable();
try
{
string filenname=#"C:\Users\sani singh\Documents\Excel03.xls";
string sWorkbook = "[Sheet1$]";
string ExcelConnectionString=#"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source="+filenname+";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection OleDbConn = new OleDbConnection(ExcelConnectionString);
OleDbConn.Open();
OleDbCommand OleDbCmd = new OleDbCommand(("SELECT * FROM " + sWorkbook),
OleDbConn);
DataSet ds = new DataSet();
OleDbDataAdapter sda = new OleDbDataAdapter(OleDbCmd);
sda.Fill(ds);
dt = ds.Tables[0];
OleDbConn.Close();
}
catch(Exception ex)
{
Response.Write(ex);
}
return dt;
}
}
}
Add a DataTable which can hold the Excel data generated via OLEDb.
string excelconnectionstring = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath + ";Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text;Jet OLEDB:Max Buffer Size=256;");
using (OleDbConnection oledbconn = new OleDbConnection(excelconnectionstring))
{
using (OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn))
{
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
dtBulkUpload.Load(dr);
}
}
Then serialize this DataTable to XML which can be sent to SQL Stored Proc. This approach is very useful if there are too many fields and you can send all in a single parameter
using (StringWriter strXML = new StringWriter())
{
dtBulkUpload.TableName = "BulkUpload";
dtBulkUpload.WriteXml(strXML, XmlWriteMode.IgnoreSchema, false);
xmlString = strXML.ToString();
}
using (SqlCommand cmd = new SqlCommand("Stored PROC Name"))
{
cmd.Parameters.AddWithValue("#dtBulkUpload", bulkUploadData);
//SqlParameter returnParameter = cmd.Parameters.Add("#result", SqlDbType.NVarChar);
//returnParameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add("#result", SqlDbType.NVarChar,3000);
cmd.Parameters["#result"].Direction = ParameterDirection.Output;
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
query = (string)(cmd.Parameters["#result"].Value.ToString());
con.Close();

Error when opening dbf file: External table is not in expected format

I'm using the code below to import a dbf file.
But I am getting an error:
'External table is not in expected format'
if (ofdDBF.ShowDialog()==DialogResult.OK)
{
string connStr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ofdDBF.FileName.Substring(0, ofdDBF.FileName.LastIndexOf("\\")) + ";Extended Properties=dBASE IV;";
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
string cmd_string = "select * from " + ofdDBF.SafeFileName.Substring(0, ofdDBF.SafeFileName.IndexOf("."));
MessageBox.Show(cmd_string);
OleDbDataAdapter da = new OleDbDataAdapter(cmd_string, conn);
DataSet ds = new DataSet();
da.Fill(ds);
dgvImport.DataSource = ds.Tables[0];
}
Any help?
Same problem (on 64Bit Systems), solution
Download: http://download.microsoft.com/download/b/f/b/bfbfa4b8-7f91-4649-8dab-9a6476360365/VFPOLEDBSetup.msi
string connString = #"Provider=vfpoledb;Data Source=C:\Directory;Collating Sequence=machine;";
using (OleDbConnection con = new OleDbConnection(connString))
{
con.Open();
OleDbCommand command = new OleDbCommand("Select * from Table.DBF", con);
OleDbDataReader reader = command.ExecuteReader();
...
}
When dealing with data sources for dBase/FoxPro, the source typically refers to EITHER a Database name, or just the path.
Once that is opened, you can just do
select * from YourTable
(no .dbf file name suffix required in the query. It will resolve itself by looking in the path or the connected database).

Categories