如何使用for循环一次读取一个csv?

时间:2013-12-30 05:44:08

标签: c# asp.net

string todate = txtToDate1.Text;
string fromtime = DropDownList2.SelectedItem.Text;
string totime = DropDownList3.SelectedItem.Text;

string fromdatetime = fromdate + "_" + fromtime;
string todatetime = todate + "_" + totime;


con.ConnectionString = constr;

//create instance for command object 
OleDbCommand cmd = new OleDbCommand();


cmd.Connection = con;   
// set your file name in the below query
cmd.CommandText = "select * from " + fromdatetime + ".csv ";



//Open Oledb Connection to read CSV file 
con.Open(); 

//Create one datatable to store data from CSV file
DataTable dt = new DataTable();

// Load Data into the datatable 
dt.Load(cmd.ExecuteReader());

字符串fromdatetime类似于12162013_0730.csv,字符串todatetime类似于12162013_0930.csv ...我如何使用for循环来读取fromdatetime todatetime之间的文件...阅读12162013_0730.csv,12162013_0830.csv, 12162013_0930.csv,一次一个文件?

1 个答案:

答案 0 :(得分:1)

如果您当前的代码工作正常,那么像下面这样的事情就可以完成工作

DateTime start = DateTime.ParseExact("09162014_0830", "MMddyyyy_hhmm", CultureInfo.InvariantCulture);
DateTime end = DateTime.ParseExact("11162014_0830", "MMddyyyy_hhmm", CultureInfo.InvariantCulture);

               con.open()
               var dt = new DataTable();
               while (start <= end)
               {
                   string csvname = start.ToString("MMddyyyy_hhmm")+".csv";
                   cmd.CommandText = "select * from " + csvname ;
                   var tempdt = new DataTable();
                   tempdt.Load(cmd.ExecuteReader());
                   dt.Merge(tempdt);
                   start = start.AddHours(1d);
               }
               con.close()

现在dt在这些日期之间保存csv文件中的所有数据,请确保处理异常。