How to read Excel file in c# by connection string? - c#

How to read the excel file and show its data in grid view ? I tried the ODBC provider its working but, it is happening win "Dns=EXCELF", how it will possible with connection sring ? I generate my Excel sheet connection string as :
Provider=MSDASQL.1;Persist Security Info=False;User ID=admin;Data Source=Excel Files;Initial Catalog=D:\Parallelminds\Tryouts\sample.xlsx
Is that wrong ? please guide me. which connection string i have to give there...?

It varies somewhat by version of Excel, but if this is pre-2007, you can find what you need here: http://connectionstrings.com/excel
Otherwise, browse http://connectionstrings.com/. It's there somewhere, I promise :).

public string BuildExcelConnectionString(string Filename, bool FirstRowContainsHeaders){
return string.Format("Provider=Microsoft.Jet.OLEDB.4.0;
Data Source='{0}';Extended Properties=\"Excel 8.0;HDR={1};\"",
Filename.Replace("'", "''"),FirstRowContainsHeaders ? "Yes" : "No");
}
public string BuildExcel2007ConnectionString(string Filename, bool FirstRowContainsHeaders){
return string.Format("Provider=Microsoft.ACE.OLEDB.12.0;
Data Source={0};Extended Properties=\"Excel 12.0;HDR={1}\";",
Filename.Replace("'", "''"),FirstRowContainsHeaders ? "Yes" : "No");
}
private void ReadExcelFile(){
string connStr = BuildExcel2007ConnectionString(#"C:\Data\Spreadsheet.xlsx", true);
string query = #"Select * From [Sheet1$] Where Row = 2";
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connStr);
conn.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(query, conn);
System.Data.OleDb.OleDbDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dr.Close();
conn.Close();
}

This Excel Data Provider is very handy. I recently used it on one of my client's websites with a few minor customizations. If you look through the code you should be able to get a solid idea of how to query Excel from C#.
Just a warning: if Excel is not installed on the deployment machine then you will be restricted to parsing standard XLS files (Office thru 2003), and will not be able to read XLSX (Office 2007).

Related

C# ace oledb 12 read-only file

I have a SSIS package with script task. c# script use ACE Oledb 12.0 provider to connect to excel file. The question is, how to connect to excel file in read-only mode (if someone open the file, my script should not have an error - it should work). The code, I tried here:
string fileToTest = Dts.Variables["User::FileName"].Value.ToString();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + fileToTest + #";Extended Properties=""Excel 8.0;READONLY=1""";
OleDbConnection excelConnection = new OleDbConnection(connectionString);
excelConnection.Open();
string sqlQuery = "SELECT * FROM [SheetName$A1:FZ1000]";
OleDbDataAdapter dataAdt = new OleDbDataAdapter(sqlQuery, excelConnection);
DataSet dataSt = new DataSet();
dataAdt.Fill(dataSt, "TblName1");
DataTable dataTbl = dataSt.Tables["TblName1"];
I receive oledbexception, if someone open the file.
Use google to search for that.
I searched for: "microsoft.ace.oledb.12.0 read only"
https://social.msdn.microsoft.com/Forums/office/en-US/498cd52a-b0ee-4c8d-8943-2b76055b4130/oledbconnection-read-only-mode?forum=accessdev
It looks like you can add to the connection string.
From that page:
Actually, with an OleDbConnection (assuming .net here). You can specify a read only mode in your connection string of the OleDbConnection. The following connection string will prevent you from changing data in your datasource:
const string cnnString = "Provider=Microsoft.ACE.OLEDB.12.0"
+ ";Mode=Read"
+ #";Data Source=|DataDirectory|\Northwind 2010.accdb";
It looks like adding ;Mode=Read to the connection string should do the trick.

Error connecting to Excel spreadsheet

Have no idea what I'm doing wrong here but I keep getting the following exception on the connection.Open(); line:
IErrorInfo.GetDescription failed with E_FAIL(0x80004005)
Problem is I have almost the exact same code in another batch job and it works fine. We even pull a spreadsheet from the same location. Does anyone see anything wrong with my connection or query string?
static void Main(string[] args)
{
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= \\prdhilfs03\l&i-sales&mkt\WORKAREA\Agencyservices\Shared\AIC\Analysts_and_Reporting\Realignments\2014\MassUpdateTesting\ZipCodeTest.xslx;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
string queryString = "SELECT * FROM [Query1$]";
try
{
OleDbDataReader reader;
using (OleDbConnection connection = new OleDbConnection(connString))
{
//Set connection objects to pull from spreadsheet
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
For good measure here's a screen shot of the workbook I'm trying to connect to
Did you try to check if you can access the file?
string xlFile = #"\\prdhilfs03\l&i-sales&mkt\......\ZipCodeTest.xlsx";
Console.WriteLine(File.Exists(xlFile) ? "Excel File exists." : "Excel File does not exist.");

Getting different errors while importing Excel file through SqlBulkCopy

I am importing an Excel file into SQL Server using SqlBulkCopy
But every time I get differant errors like
Cannot update. Database or object is read-only.
or
Could not find installable ISAM.
or
The Microsoft Jet database engine could not find the object. Make sure the object exists and that you spell its name and the path name correctly.
Check my code below...
String strConnection = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
string excelConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+filepath+";Extended Properties=Excel 8.0;HDR=YES;";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand
("Select * from [Sheet1$]",
excelConnection);
MessageBox.Show("ss");
excelConnection.Open();
MessageBox.Show("ss2");
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
MessageBox.Show("ss1");
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "RecExcelTable";
//sqlBulk.ColumnMappings.Add("ID", "ID");
//sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.WriteToServer(dReader);
Also I need to compitable this code for any version of Excel.
How can I do that and solve my error?
I had similar issue. Check that the file path is correct
do like
C:\\file.xls
as a test.
And also check that the version is correct. 8.0 is pretty old I think thats like office 2000, no ?

C# code to read Excel (html import)

I trying to read Excel file which is Html type with C# code.
I'm getting an 'Unspecified error'.
This is my connection string:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='HTML Import; // c:\1.xls
This is my code:
private string GetTableName(OleDbConnection conn)
{
string tableName = null;
try
{
conn.Open();
var dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
log.Error("Table schema is not available.");
return tableName;
}
tableName = dt.Rows[0]["TABLE_NAME"].ToString();
}
catch (Exception e)
{
log.Warn(e);
return null;
}
finally
{
conn.Close();
}
return tableName;
}
I looked all over the Internet and Google and nobody had exactly the same issue.
I would like to understand what is wrong with my code or what does it mean the 'Unspecified Error'?!
Thanks !!!
Try using
Provider=Microsoft.ACE.OLEDB.12.0;
Edit:
Use this connection string
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\";"
HDR=Yes means that the header is considered as a data row and not column names (Change it depending on your needs)
IMEX=1 specify that the table contains mixed data
for Excel 2007 change connection string as
Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0 Xml;HDR=YES';
ACE OLEDB 12.0 was released with Office 2007. It is possible to use the Microsoft.ACE.OLEDB.12.0 to connect to older .xls (Excel 97-2003) workbooks as well.

Excel contents into SQL Server table using Visual Studio 2008

I'm creating an application where the user clicks on a button, browses for an Excel file, and the data is copied into the data table created in the database.
I am using VS2008 and SQL Server 2005.
I wrote code for opening the file of course, and created a dataTable and its dataColumns in the .cs file. What else should I do?
Thank you.
You could do as Krishna advises... but that code will only work if the columns in the excel file and Database columns are the same in number and order. For ease of maintainability and mapping down the line I highly recommend you use a combination of Linq to Excel and Linq to SQL as in this article:
http://solidcoding.blogspot.com/2008/01/linq-to-excel-sql-import.html
You can write like the code below to dump the data into the SQL Server table
string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("ImportFile.xls") + ";Extended Properties=""Excel 8.0;HDR=Yes;""";
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select * FROM [NameOfTheDataSheet$]", connection);
connection.Open();
using (DbDataReader dataReader = command.ExecuteReader())
{
string sqlConnectionString = "SQL Connection String";
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelDataTable";
bulkCopy.WriteToServer(dataReader);
}
}
}
Let me know if you have different requirements.

Categories

Resources