How to read a password protected Excel worksheet with OLEDB - c#

I have set a password on my excel sheet. To unlock the worksheet, I modified my OLEDB connection string, but it didn't work. I got an error that "the source contains no dataRows", which means that it couldn't read the data from the excel file.
Before it was fine. What might be my problem?
This is my code:
public DataTable getExcelData(string fileName, string sheetName, ComboBox[] User_ComboBox)
{
this.m_comboBox = User_ComboBox;
// connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + fileName + "';Extended Properties= 'Excel 12.0 XML;HDR=No;IMEX=1'";
connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Password=xyz;Extended Properties='Excel 8.0;HDR=YES'";
string errorMessage = "";
DataTable dt = new DataTable();
try
{
string query = "SELECT * FROM [" + sheetName + "]";
OleDbConnection con = new OleDbConnection(connectionString);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, con);
dataAdapter.Fill(dt);
}
catch (Exception exp)
{
// errorCode = ErrorDefinition.ERROR_OLEDBERROR;
errorMessage = exp.Message;
}
return dt;
}

Instead of using an OleDbConnection you might consider using an Excel reading library like EPPlus to read the excel file. EPPlus supports reading password protected excel files.
You would need to implement some code to build the actual DataTable, but that should be simple enough. Just google it if you need to.

Related

How to prevent OLEDB create new excel file when path in connection string not exist

Example:
public static DataTable dTable;
public bool openDBSheet(string sheet)
{
String str=
"Provider=Microsoft.ACE.OLEDB.12.0;"
+ #"Data Source=D:\Item1.xlsx;"
+"Extended Properties='Excel 12.0 XML;HDR=Yes'";
try
{
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + sheet + "$]", conn);
dTable = new DataTable();
adapter.Fill(dTable);
conn.Close();
}
catch (Exception)
{
return false;
}
return true;
}
The real file name is "Item.xlsx" but when I change the path to "D:\Item1.xlsx;" (that not exist) the program create a new empty file named "Item1.xlsx".
Can anyone please explain me why and how to solve it?
Or maybe there's another better way to validate not exist excel file using OLEDB ???
You can use File.Exists()
if (!File.Exists(#"D:\Item1.xlsx"))
return;

EPPLUS import excel file without header ASP.net

Hi is it possible to read an excel file without headers using EPPLUS?
You can save the excel in csv format and skip the first line after reading all line.
var lines = File.ReadAllLines(FileName).Skip(1);
or you can use oledb connection to import data from excel to datatable .
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filename + ";" + "Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';";
string query = string.Format("SELECT * FROM [{0}$]", tablename);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString))
{
DataSet jobDataSet = new DataSet();
dataAdapter.Fill(jobDataSet, "jobInfo");
DataTable jobDataTable = jobDataSet.Tables["jobInfo"];
}

Reading a spreadsheetl file from fileupload control into filestream

I am trying to find the best way of selecting an excel spreadsheet (xls and xlsx) using a fileupload control and then parsing it with filestream object and then populating a dataset.
This is my code so far which does the job but how it differs is I am saving the excel spreadsheet to a folder in my solution then querying the data using Microsoft ACE OLEDB connection.
protected void btnUpload_Click(object sender, EventArgs e)
{
string connectingString = "";
if (ctrlFileUpload.HasFile)
{
string fileName =
Path.GetFileName(ctrlFileUpload.PostedFile.FileName);
string fileExtension =
Path.GetExtension(ctrlFileUpload.PostedFile.FileName);
//Path.GetExtension(ctrlFileUpload.PostedFile.ContentType);
string fileLocation =
Server.MapPath("~/App_Data/" + fileName);
ctrlFileUpload.SaveAs(fileLocation);
// Check whether file extension is xls or xslx
if (fileExtension == ".xls")
{
connectingString =
"Provider=Microsoft.ACE.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectingString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=2\"";
}
// Create OleDb Connection and OleD Command
using (OleDbConnection con = new OleDbConnection(connectingString))
{
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
//DataTable dtExcelRecords = new DataTable();
DataSet ds = new DataSet();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "Select * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
//dAdapter.Fill(dtExcelRecords);
dAdapter.Fill(ds);
//GridView1.DataSource = dtExcelRecords;
//GridView1.DataBind();
}
catch (Exception ex)
{
}
}
}
}
So to summarise I want to read the data in a spreadsheet and then bind it to a dataset but without saving the file to a physical path.
Is there a cleaner way of writing this code that I am missing. Thanks!!
I think it not possible to get data without save file to your server
If you can't save uploded file how can you give Data Source to your oleDbConnection string ??
you can delete file after finish this execution if you don't want to keep the file.
you can also refer this way https://stackoverflow.com/a/12420416/284240

Working with Excel files in C#

I have Excel files that are in 2000 & 2003 format. I need to import them via C# code into an access DB. I have written a method to read the file into a data table. No matter which connection string i use (I have checked the other posts on this topic) I continue to get "Table is not in the correct format" error. Can someone please explain to me what I am doing wrong.
public static DataSet ParseExcel(string excelFile)
{
string sheetName = Path.GetFileNameWithoutExtension(excelFile);
string excelQuery = #"SELECT * FROM [" + sheetName + "]";
string excelConnctionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "" + excelFile + "" +
#";Extended Properties=" + "" + #"Excel 8.0;HDR=Yes;" + "";
if(File.Exists(excelFile))
{
var myConnection = new OleDbConnection(excelConnctionString);
myConnection.Open();
var myCommand = new OleDbDataAdapter(excelQuery, excelConnctionString);
myCommand.TableMappings.Add("Table", "TestTable");
var dtSet = new DataSet();
myCommand.Fill(dtSet);
myConnection.Close();
return dtSet;
}
return null;
}
Go through this code example carefully and try to understand the work flow. You will get it real easy to write any kind programs for accessing excel data according to your requirements.
1.Here I just have a Upload Field in order to select the Excel File in .aspx file
<asp:FileUpload ID="Upload_File" runat="server" />
<asp:Button ID="Upload_Button" runat="server" Text="Upload" onclick="btnUpload_Click"/>
<asp:GridView ID="Gridview_Name" runat="server">
</asp:GridView>
Now lets see what happens in code behind file (.aspx.cs file)
protected void Upload_Button_Click(object sender, EventArgs e)
{
string connectionString = "";
if (Upload_File.HasFile) // checking whether file is selected to be uploaded
{
//getting name of the file
string fileName = Path.GetFileName(Upload_File.PostedFile.FileName);
//getting extension of the file (for checking purpose - which type .xls or .xlsx)
string fileExtension = Path.GetExtension(Upload_File.PostedFile.FileName);
string fileLocation = Server.MapPath("" + fileName); //exact location of the excel files
Upload_File.SaveAs(fileLocation);
//Check whether file extension is xls or xslx
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
//Create OleDB Connection and OleDb Command
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
//cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
con.Close();
Gridview_Name.DataSource = dtExcelRecords;
GridView_Name.DataBind();
}
else
{
Response.Write("Please Select a File to extract data ");
}
}
Step by Step Explanation :
We get the file name, extension, location .
And check it is the type (.xls or .xlsx - particularly for excels of 2003 or other formats).
Set connection strings according to the previous step.
Open oledb connection
Create the necessary data adapter and data table
open the connection
store the current table( where the data from excel is stored) in a datatable instance
Store the name of the sheet in astring by getting it from the current table
Fill the data adapter object(dAdapter) with the our data table (dtExcelRecords)
close the connection
Set datasource for the grid as out data table.
Bind it with our grid.
...And We are done!
Hope it helps.
Try this
OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";

Read alphanumeric characters from csv file in C#

I am using the following code to read my csv file:
public DataTable ParseCSV(string path)
{
if (!File.Exists(path))
return null;
string full = Path.GetFullPath(path);
string file = Path.GetFileName(full);
string dir = Path.GetDirectoryName(full);
//create the "database" connection string
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=\"" + dir + "\\\";"
+ "Extended Properties=\"text;HDR=Yes;FMT=Delimited\"";
//create the database query
string query = "SELECT * FROM " + file;
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
//fill the DataTable
dAdapter.Fill(dTable);
dAdapter.Dispose();
return dTable;
}
But the above doesn't reads the alphanumeric value from the csv file. it reads only i either numeric or alpha.
Whats the fix i need to make to read the alphanumeric values? Please suggest.
I suggest you use A Fast CSV Reader which does not have this issue and is much more faster.
Remove IMEX=1 from the connection string. I don't think you need it for CSV files.
Try this OleDBAdapter Excel QA I posted via stack overflow.
I have not tried this out, but it sounds interesting! LinqToExcel
they say it can be used on .CSV files as well...
hi all this code is gets alphanumeric values also
using System.Data.OleDb;
string ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filepath + ";" + "Extended Properties="+(char)34+"Excel 8.0;IMEX=1;"+(char)34;
string CommandText = "select * from [Sheet1$]";
OleDbConnection myConnection = new OleDbConnection(ConnectionString);
myConnection.Open();
OleDbDataAdapter myAdapter = new OleDbDataAdapter(CommandText, myConnection);
ds = null;
ds = new DataSet();
myAdapter.Fill(ds);

Categories

Resources