Reading *.csv file values is very simple. I will show you in the next few lines :
private void btnImportExcelToDb_Click(object sender, EventArgs e)
{
if (txtExcelPath.Text != "")
{
FileInfo f = new FileInfo(txtExcelPath.Text);
if (f.Extension ==".csv" )
{
todb(numbers(txtExcelPath.Text));
}
else {
MessageBox.Show( "File is not valid excel type!","WRONG FILE TYPE!",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
}
}
in button event click I write check if the file that we read is file with *.csv extension and if so, then I call 2 methods that make magic :)
Method which I use for reading a values in string array of lines :
private string[] numbers(string filepath)
{
string[] ar = null;
try
{
using (StreamReader sr = new StreamReader(filepath))
{
String line;
ar = sr.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.None);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return ar;
}
"\r\n" this is line break string characters :
and after that I call another method todb(string[] ar)
a method that use string array as parameter
private void todb(string[] ar)
{
con = new DataClasses1DataContext();
int br = 0;
for (int i = 1; i < ar.Length-1;i++ )
{
tbl_ImportedNumber t = new tbl_ImportedNumber();
string[] li=ar[i].Split(';');
t.anrede = li[0];
t.vorname = li[1];
t.nachname = li[2];
t.strasse = li[3];
t.plz = li[4];
t.ort = li[5];
t.gebdat = li[6];
t.telefon0043 = li[7];
t.telefon = li[8];
t.land = li[9];
t.date = DateTime.Now.Date;
t.@checked = false;
con.tbl_ImportedNumbers.InsertOnSubmit(t);
con.SubmitChanges();
br++;
} lblCount.Text = br.ToString();
}
in this method i read values from line and use a linq to store values in database :)
thats all code, any question ? Ask :)
- Blogger Comment
- Facebook Comment
Subscribe to:
Post Comments
(
Atom
)
0 comments:
Post a Comment