Read alphanumeric characters from csv file in C# - 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);

Related

Defining OleDbCommand Return Type

I'm using the below OleDbCommand to read from a file method multiple times. The problem I'm having is that most of the time it's returning the datatypes as strings but occasionally (depending on the data being read) its returning int types. Is there a way to request all columns return as string without having to convert everything once it's loaded?
static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
{
string header = isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string sql = #"SELECT * FROM [" + fileName + "]";
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}
If it's necessary to execute this using an OleDbCommand then you could use an OleDbDataReader instead of a DataTable and read each value using GetObject.
Then you can call ToString() on any of the values.
But if you have a CSV file containing untyped data then it might be much easier to just to read the file one line at a time and split the values, creating a List<string[]>.
This answer shows the simplest way to read a .csv and split each line.
This answer shows how to do it if the values contain commas within quotes that don't delimit values, like this,are,separate,"this,is,one"

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"];
}

Update a dbf file with datagridview in C#

Recently my mentor asked me to write a program,manipulating the dbf file in C#.I'm using Odbc & OleDb and now I can read the dbf to datagridview with a dataset.
My question is : how can I input some data in datagridview after reading from the local dbf file and update my input to the local dbf file?
I am new to this, not familiar with relevent APIs so example codes would be a great help.
Here is my code to read the dbf file to datagridvie
string filePath = #"C:\Users\csj\Desktop\db\ZMT.dbf";
FileInfo fi = new FileInfo(filePath);
string mulu = fi.DirectoryName;
string filename = fi.Name;
OleDbConnection conn = new OleDbConnection();
string table = filePath;
string connStr = #"Provider=VFPOLEDB.1;Data Source=" + mulu + ";Collating Sequence=MACHINE";
conn.ConnectionString = connStr;
conn.Open();
string sql = #"select * from " + filename;
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
DataSet dt = new DataSet();
da.Fill(dt);
conn.Close(); conn.Dispose();
dataGridView1.DataSource = dt.Tables[0].DefaultView;
Any help?
You should create a OleDbCommandBuilder after you created your OleDbDataAdapter
var builder = new OleDbCommandBuilder(da);
The builder creates Update, Insert and Delete commands for the OleDbDataAdapter.
Then after you made changes in the grid you simply call
da.Update(dt);
That's how it should work ... but I didn't try this for dbfs ...

How to read a password protected Excel worksheet with OLEDB

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.

How to handle invalid characters in OleDb Excel import?

I am importing excel files to my application and sometimes worksheets column names have "$" sign in it. I receive this Exception:
System.Data.OleDb.OleDbException was unhandled
Message=''6um$'$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long.
In this sheet "6um$" is a column name.
This is my code:
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
OleDbDataAdapter cmd = new System.Data.OleDb.OleDbDataAdapter(
"select * from [" + worksheetName + "$]", con);
con.Open();
System.Data.DataSet excelDataSet = new DataSet();
cmd.Fill(excelDataSet);
con.Close();
Any ideas how to handle this situation?
Edit:
I thought the problem was having $ in column name. But turns out, The problem is having $ sign in worksheet name!
Ok, I figured out the solution:
For some reason, the worksheets that I renamed myself have extra $ sign (no idea why, there is no $ sign in the excel but OLEDB returns them with extra $ something like this '6um$'$'). I trim the first $ off and use this code to check is there is any extra $ sign still left:
char delimiterChars = '$';
string[] words = worksheetName.Split(delimiterChars);
worksheetName=words[0];
if (Directory.Exists(serverPath))
{
string FileExist = sp + "book1.xlsx"; ;
string Exten = Path.GetExtension(FileExist);
string g = "sheet1";
if (File.Exists(FileExist))
{
if (Exten == ".xlsx")
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileExist + ";Extended Properties=Excel 12.0";
OleDbConnection oledbConn = new OleDbConnection(connString);
try
{
// Open connection
oledbConn.Open();
string query = String.Format("select * from [{0}$]", g);
// Create OleDbCommand object and select data from worksheet Sheet1
OleDbCommand cmd = new OleDbCommand(query, oledbConn);
// Create new OleDbDataAdapter
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
// Create a DataSet which will hold the data extracted from the worksheet.
DataSet ds = new DataSet();
// Fill the DataSet from the data extracted from the worksheet.
oleda.Fill(ds, "sheetdt");
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
catch (Exception ex)
{
LblSuccess.Text = ex.Message;
}
finally
{
// Close connection
oledbConn.Close();
}
}
}
}

Categories

Resources