data source folder on other device - c#

we have data stored in an Excel file (Trail_Test.xls), which is stored in the Resources folder of our C# project.
now we need to load data from that xls file to dataGridView on the windows form application we have.
This is the code we use
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand;
string path = System.AppDomain.CurrentDomain.BaseDirectory + #"Resources\Trail_Test.xls";
MyConnection = new System.Data.OleDb.OleDbConnection(#"provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + path + "';Extended Properties=Excel 8.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [20$]", MyConnection);
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dataGridView1.Columns.Clear();
dataGridView1.DataSource = DtSet.Tables[0];
This gives an error on the 8th line:
The Microsoft Jet database engine could not find the object '20$'. Make sure the object exists and that you spell its name and the path name correctly.
any help ??
thanks

The path has to be relative to the executable. For example if the executable is in
C:\Users\Adham\Documents\Visual Studio 2010\Projects\Curve Fitting\Curve Fitting\
then the path to the .xls file will be
string path = System.AppDomain.CurrentDomain.BaseDirectory + #"Resources\Trail_Test.xls";
string connectionString = #"provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + path + "';Extended Properties=Excel 8.0;"

Your MyConnection object includes
Data Source='C:\Users\Adham\Documents\Visual Studio 2010\Projects\Curve Fitting\Curve Fitting\Resources\Trail_Test.xls
that looks like something that should not be hardcoded and will cause problems when executed on any other computer but Adham's.

Try this: Make sure that the file is marked as "Copy to output directory=copy if newer", just right click on it and see "properties"

you should reach the installition folder. It will depends on your project type. There is an answer to reach Resources folder for a c# project
https://stackoverflow.com/a/27182028/3209523

Related

SSIS Excel C# Import Script returns empty table when importing xlsx file saved by other users

I have created a SSIS import task, where in For Each Loop container I have Data Flow Task, in which I have Script Component where I try to import xlsx files from external drive folder to upload to database.
My excel connection method is:
private DataTable QueryData(string FileName, string Header, string QueryString)
{
string connectionString;
OleDbConnection excelConnection;
OleDbDataAdapter dataAdapter;
DataSet excelDataSet;
connectionString = "Provider = Microsoft.ACE.OLEDB.16.0; Data Source ="
+ FileName + ";Extended Properties=\"Excel 12.0 XML;HDR= "
+ Header + ";IMEX=1;\"";
excelConnection = new OleDbConnection(connectionString);
dataAdapter = new OleDbDataAdapter(QueryString, excelConnection);
excelDataSet = new DataSet();
dataAdapter.Fill(excelDataSet, "Sheet1");
excelConnection.Close();
return excelDataSet.Tables["Sheet1"];
}
The Script component works fine with files saved by me.
When the component tries to get information from Excel files that are saved by others, the method returns only one row with empty object[].
I have tried unsuccessfully to Run the SSIS as Administrator and also in the server as I suspect there might be problems with file permissions.

How to determine whether excel workbook is password protected or not in C# using OLEDB?

I am reading an excel file using 'OLEDB'. I need a provision where I can determine whether excel file that I am accessing is password protected or not. Please find my code below:
private DataSet LoadExcel(string fileName, string tableName)
{
string path = fileName;
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand;
MyConnection = new System.Data.OleDb.OleDbConnection(connStr);
MyConnection.Open();
DataTable dtExcelSchema;
dtExcelSchema = MyConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + SheetName + "]", MyConnection);
MyCommand.TableMappings.Add("Table", tableName);
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
MyConnection.Close();
return DtSet;
}
My code is breaking up on line "MyConnection.Open();" because the excel file which it is accessing here is password-protected. If I could check that, I will bypass the code and display a user-friendly message. Please help if anyone has any idea on this front.
Thanks in Advance!!
From http://www.connectionstrings.com/excel/
If the Excel workbook is protected by a password, you cannot open it for data access, even by supplying the correct password with your connection string. If you try, you receive the following error message: "Could not decrypt file."
OLEDB connection will not work for password protected worksheets. If there is some exception, you can detect the exact type and catch it.
Other way is to use the Office API and use the HasPassword property.
Workbook book = '.....xyz''';
if (book.HasPassword) { ... }
Have you tried sth like that?
try
{
MyConnection.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Per Aseem's first response, the "Could not decrypt file." problem is a result of the Excel file not being in a trusted location. I had the same problem and solved it by moving the Excel file to a trusted location or adding the folder that the Excel file is in to the Trusted Locations.

xlsx file upload not working correctly - works when file is open but not when closed

I've been doing research on this problem for about a day and a half and haven't found a solution to my problem yet. This is my scenario:
I have a AsyncFileUpload and a button which is configured to accept only xls and xlsx files (Excel) file. This file that is uploaded is used to import information into a gridview. The old format xls files works fine. The problem comes when I want to upload the xlsx file. I've tested multiple scenarios and I have found that it works perfectly when the xlsx file is currectly/actively open. When it is closed it gives me errors. I have fiddled and explored solutions to this problem and the range of errors I have received is quite large. But the most prominent errors where the following:
1. External table is not in the expected format.
2. could-not-find-installable-isam
I have found an article relating to the second error (Could not find installable ISAM) but I haven't tried all the suggested solutions yet because I would rather avoid making changes to the windows registry because I do not have exstensive knowledge regarding this matter.
I'm attaching the code that I use to make the connection between the OleDb and the excel file:
protected void AsyncUpload_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string connString = "";
string strFileType = Path.GetExtension(e.FileName).ToLower();
string path = e.FileName;
////Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;HDR=Yes;IMEX=1";
}
string query = "SELECT * FROM [sheet1$]";
OleDbConnection conn = new OleDbConnection(connString);
if (conn.State == ConnectionState.Closed)
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
using (OleDbDataReader dr = cmd.ExecuteReader())
{
_InsertWrapper.clearLists();
while (dr.Read())
{
var row1Col0 = dr[0];
Console.WriteLine(row1Col0);
_InsertWrapper.GenerateList(dr);
}
}
da.Dispose();
conn.Close();
conn.Dispose();
InventoryGrid.DataBind();
ErrorsGrid.DataBind();
}
If someone has additional knowledge or an explanation that can contribute please add it so that more people that are struggling with the same type of problem can gain as much information from this question as possible.We are all still learning.
So, main idea: Need to find a solution to successfully upload the xlsx file
Try using third party tools. They work efficiently:
http://code.google.com/p/excellibrary/

Updating data in to a Excel sheet using c#

I am trying to update some data in an Excel sheet of the format "xlsx" using OLEDB connection, but I am unable to make out the connection establishment.
Here is my code:
String sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" + "D:\abc1.xlsx" + "';Extended Properties='Excel 8.0;HDR=Yes'";
OleDbConnection con = new OleDbConnection(sConnectionString);
con.Open();
OleDbCommand com = new OleDbCommand("select * from Sheet1",con);
OleDbDataReader reader = null;
reader = com.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0]);
}
con.Open();
Console.ReadLine();
}
When I run the code, I'm facing the following exception:
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local
machine.
Any idea how to recover from this exception or any other suggestions from which i can update my data in excel is advisable.
This could be the provider you have stated try changing it to the one which matches the Excel version on your machine
Try
Provider=Microsoft.ACE.OLEDB.12.0;Data Source='D:\abc1.xlsx';Extended Properties="Excel 12.0 Xml;HDR=YES";
Instead
Could also be that excel isnt installed
Also check that you have referenced the OLEDB library for your project
Change your PlatformTarget Type from AnyCPU to X86.
Steps:
Goto Project Properties.
Select Build tab.
Select X86 from PlatformTarget options.
It is possible that there are multiple reasons for this exception.
1) You could use the OleDbEnumerator class to find out what providers are available.
Accordingly you set your connection string.
2) Before that just try out below connection string.
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + "D:\abc1.xlsx" + "';Extended Properties='Excel 8.0;HDR=Yes'";
3) If you have a 64 bit OS, there is no 64-bit version of the JET provider available and there's no alternative. As long as you want to support JET, you'll need to set the build target to x86.
first save as your excel workbook as Excel 97-2003 Workbook
It will work in my project...
string filepath = Server.MapPath("~/ImportData/") + fileUpload.FileName;
OleDbConnection oconn = new OleDbConnection
(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";
Extended Properties=Excel 8.0");`
oconn.Open();
OleDbDataAdapter adp = new OleDbDataAdapter("select * from Sheet1", oconn);
DataSet ds = new DataSet();
adp.Fill(ds);
oconn.Close();`

Accessing folder in console application

I'm trying to write a function to read csv contents into a datatable.
I'm getting an exception about the file path and wondering what it is that I'm doing wrong.
All I did was create the console app and create a folder in the project called 'Data'.
public DataTable ReadCSV(string filename)
{
DataTable dt = new DataTable();
string sql = "SELECT * FROM " + filename;
string path = "Data\\";
string connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + filename + ";" + "Extended Properties='text;FMT=Delimited(;);HDR=YES'";
OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connstring);
System.Data.OleDb.OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
try
{
conn.Open();
da.Fill(dt);
}
catch (Exception ex)
{
Console.WriteLine(filename + "not found");
}
finally
{
conn.Close();
}
return dt;
}
}
My connection string in the Text visualizer when I run in debug mode:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Data\Positions.csv;Extended Properties='text;FMT=Delimited(;);HDR=YES'
I'm getting an exception
base {System.Data.Common.DbException} = {"'Data\Positions.csv' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides."}
Can anyone point me in the right direction? I have limited experience doing console apps so it's probably some formatting mistake that I've made. Thanks
and create a folder in the project called 'Data'.
That doesn't work. Your program is running in the bin\Debug subdirectory of your project. It doesn't have a Data subdirectory. You'd have to use ..\..\Data\Positions.csv to find that file.
Well, that would solve your problem right now but it isn't going to be useful once you copy your program to another machine. There won't be a ..\..\Data directory there. Think about ways that your user is going to tell you where the .csv file is located. A GUI with OpenFileDialog is the friendly way but not very compatible with a console app. The standard way for that is to pass command line arguments. Environment.CommandLine. Not very compatible with the typical user. You'll have to weigh these options by yourself.

Categories