1.使用OleDB操作.csv文件,比较费时
1 public static DataTable GetDataTableFromCsv(string path,bool isFirstRowHeader) 2 { 3 string header = isFirstRowHeader ? "Yes" : "No"; 4 5 string pathOnly = Path.GetDirectoryName(path);//得到文件夹路径,相当于得到要操作的“数据库” 6 string fileName = Path.GetFileName(path);//得到文件名,相当于得到要操作的数据库中的数据表 7 8 string sql = @"select * from ["+fileName+"]";//sql语句 9 //操作数据库的流程 10 using (OleDbConnection con=new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +";Extended Properties="Text;HDR=" + header + """)) 11 { 12 using (OleDbCommand cmd=new OleDbCommand(sql,con)) 13 { 14 using (OleDbDataAdapter adapter=new OleDbDataAdapter(cmd)) 15 { 16 DataTable dt=new DataTable(); 17 dt.Locale=CultureInfo.CurrentCulture; 18 adapter.Fill(dt); 19 return dt; 20 } 21 } 22 } 23 }
2. 使用文件流操作.csv文件,费时短(txt文件也可以)
1 public static DataTable ConvertCsvToDataTable(string fileName) 2 { 3 DataTable dt=new DataTable(); 4 using (StreamReader sr=new StreamReader(fileName,Encoding.UTF8)) 5 { 6 string[] headers = sr.ReadLine().Split(',');//处理头部标题 7 foreach (string header in headers) 8 { 9 dt.Columns.Add(header); 10 } 11 while (!sr.EndOfStream) 12 { 13 string[] rows = sr.ReadLine().Split(','); 14 DataRow dr = dt.NewRow(); 15 for (int i = 0; i < headers.Length; i++) 16 { 17 dr[i] = rows[i]; 18 } 19 dt.Rows.Add(dr); 20 } 21 } 22 return dt; 23 }
3.winform中应用
1 private void btnGet_Click(object sender, EventArgs e) 2 { 3 //打开文件对话框 4 OpenFileDialog ofd=new OpenFileDialog() {Filter = "Csv文件|*.csv|Excel文件|*.xls|所有文件|*.*", InitialDirectory = @"C:UsersLWP1398Desktop",RestoreDirectory = true}; 5 if (ofd.ShowDialog()==DialogResult.OK) 6 { 7 string fileName = ofd.FileName; 8 //dgv.DataSource = GetDataTableFromCsv(fileName, true); 9 dgv.DataSource = ConvertCsvToDataTable(fileName); 10 } 11 MessageBox.Show("ok"); 12 }