2012-05-08 42 views
1

我有這樣的MS Access表結構如下:如何將製表符分隔文本文件顯示到DataGridView中,包括標題?

enter image description here

我提取的數據與沒有文本識別符製表符分隔文本文件:

enter image description here

我發現this文章但它不適用於製表符分隔的文件。 我不知道如何將這些數據顯示到包含標題的DataGridView中。你能幫我麼?

在此先感謝。

+0

還沒有嘗試過自己,但我猜最簡單的途徑將文件讀入一個DataTable(如果需要的話FileHelpers庫可以幫助),然後你的DataGridView綁定到數據表。 –

回答

0
DataGridView1.DataSource = CsvFileToDatatable(@"c:\a.csv",true); 

public DataTable CsvFileToDatatable(string path, bool IsFirstRowHeader)//here Path is root of file and IsFirstRowHeader is header is there or not 
     { 
      string header = "No"; 
      string sql = string.Empty; 
      DataTable dataTable = null; 
      string pathOnly = string.Empty; 
      string fileName = string.Empty; 

      try 
      { 

       pathOnly = Path.GetDirectoryName(path); 
       fileName = Path.GetFileName(path); 

       sql = @"SELECT * FROM [" + fileName + "]"; 

       if (IsFirstRowHeader) 
       { 
        header = "Yes"; 
       } 

       using (OleDbConnection connection = new OleDbConnection(
         @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + 
         ";Extended Properties=\"Text;HDR=" + header + "\"")) 
       { 
        using (OleDbCommand command = new OleDbCommand(sql, connection)) 
        { 
         using (OleDbDataAdapter adapter = new OleDbDataAdapter(command)) 
         { 
          dataTable = new DataTable(); 
          dataTable.Locale = CultureInfo.CurrentCulture; 
          adapter.Fill(dataTable); 

         } 
        } 
       } 
      } 
      finally 
      { 

      } 

      return dataTable; 

     } 
相關問題