2010-02-24 32 views
2

這一直在殺死我 - 我有一個龐大的文件,我需要作爲一個DataTable讀入。使用Jet讀取CSV文件 - TabDelimited不工作!

很多折騰了我後我用這樣的:

using (OleDbConnection connection = new OleDbConnection(connString)) 
{ 
    using (OleDbCommand command = new OleDbCommand(sql, connection)) 
    { 
     using (OleDbDataAdapter adapter = new OleDbDataAdapter(command)) 
     { 
      dataTable = new DataTable(); 
      dataTable.Locale = CultureInfo.CurrentCulture; 
      adapter.Fill(dataTable); 
     } 
    } 
} 

如果文本文件是逗號分隔,但其作品,如果它是製表符分隔不工作 - 任何人都可以請幫助?

我的連接字符串的樣子:

string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + @";Extended Properties='text;HDR=YES'";

我已經盡力了FMT財產,沒有運氣設置....

+1

您是否嘗試過使用以下部分在同一目錄中創建schema.ini? [MyFilename.txt] Format = TabDelimited – 2010-02-24 20:05:06

回答

2

這是一個很好的圖書館使用它。

http://www.codeproject.com/KB/database/CsvReader.aspx

這裏是一個使用該庫的代碼。

TextReader tr = new StreamReader(HttpContext.Current.Server.MapPath(Filename)); 
string data = tr.ReadToEnd(); 
tr.Close(); 

用逗號分隔;

CachedCsvReader cr = new CachedCsvReader(new StringReader(csv), true); 

for tab delimited;

CachedCsvReader cr = new CachedCsvReader(new StringReader(csv), true, '\t'); 

在這裏,你可以有這個代碼

DataTable dt = new DataTable(); 
dt.Load(cr); 

希望你覺得它有用它加載到數據表。謝謝

+0

而且,您只需將此函數作爲字符串數組調用即可輕鬆獲得csv文件的頭文件。 cr.GetFieldHeaders(); – 2010-02-24 18:50:10

+1

我已經用這個庫成功,所以給它一個投票 – 2010-02-24 20:06:14

+0

是的,但這將工作與製表符分隔,而不是csv? – 2010-02-24 20:13:21

-1

這應該工作:(從http://www.hotblue.com/article0000.aspx?a=0006

只需用逗號部分替換:

if ((postdata || !quoted) && (c == ',' || c == '\t')) 

以使其製表符分隔。

using System.Data; 
using System.IO; 
using System.Text.RegularExpressions; 

public DataTable ParseCSV(string inputString) { 

    DataTable dt=new DataTable(); 

    // declare the Regular Expression that will match versus the input string 
    Regex re=new Regex("((?<field>[^\",\\r\\n]+)|\"(?<field>([^\"]|\"\")+)\")(,|(?<rowbreak>\\r\\n|\\n|$))"); 

    ArrayList colArray=new ArrayList(); 
    ArrayList rowArray=new ArrayList(); 

    int colCount=0; 
    int maxColCount=0; 
    string rowbreak=""; 
    string field=""; 

    MatchCollection mc=re.Matches(inputString); 

    foreach(Match m in mc) { 

    // retrieve the field and replace two double-quotes with a single double-quote 
    field=m.Result("${field}").Replace("\"\"","\""); 

    rowbreak=m.Result("${rowbreak}"); 

    if (field.Length > 0) { 
     colArray.Add(field);     
     colCount++; 
    } 

    if (rowbreak.Length > 0) { 

     // add the column array to the row Array List 
     rowArray.Add(colArray.ToArray()); 

     // create a new Array List to hold the field values 
     colArray=new ArrayList(); 

     if (colCount > maxColCount) 
     maxColCount=colCount; 

     colCount=0; 
    } 
    } 

    if (rowbreak.Length == 0) { 
    // this is executed when the last line doesn't 
    // end with a line break 
    rowArray.Add(colArray.ToArray()); 
    if (colCount > maxColCount) 
     maxColCount=colCount; 
    } 

    // create the columns for the table 
    for(int i=0; i < maxColCount; i++) 
    dt.Columns.Add(String.Format("col{0:000}",i)); 

    // convert the row Array List into an Array object for easier access 
    Array ra=rowArray.ToArray(); 
    for(int i=0; i < ra.Length; i++) {     

    // create a new DataRow 
    DataRow dr=dt.NewRow(); 

    // convert the column Array List into an Array object for easier access 
    Array ca=(Array)(ra.GetValue(i));    

    // add each field into the new DataRow 
    for(int j=0; j < ca.Length; j++) 
     dr[j]=ca.GetValue(j); 

    // add the new DataRow to the DataTable 
    dt.Rows.Add(dr); 
    } 

    // in case no data was parsed, create a single column 
    if (dt.Columns.Count == 0) 
    dt.Columns.Add("NoData"); 

    return dt; 
} 

現在,我們有一個字符串轉換成一個DataTable解析器,現在我們需要的是將讀取一個CSV文件中的內容並把它傳遞給我們的ParseCSV功能的函數:

public DataTable ParseCSVFile(string path) { 

    string inputString=""; 

    // check that the file exists before opening it 
    if (File.Exists(path)) { 

    StreamReader sr = new StreamReader(path); 
    inputString = sr.ReadToEnd(); 
    sr.Close(); 

    } 

    return ParseCSV(inputString); 
} 

現在你可以很容易地用數據填充脫落的CSV文件的數據網格:

protected System.Web.UI.WebControls.DataGrid DataGrid1; 

private void Page_Load(object sender, System.EventArgs e) { 

    // call the parser 
    DataTable dt=ParseCSVFile(Server.MapPath("./demo.csv"));   

    // bind the resulting DataTable to a DataGrid Web Control 
    DataGrid1.DataSource=dt; 
    DataGrid1.DataBind(); 
} 
+0

這有什麼問題。它效果很好。 – 2010-02-24 20:54:29

0

手動:您可以使用String.Split()方法來分割你的整個文件。以下是我在代碼中使用的示例。在這個例子中,我一行一行地讀取數據並分割它。然後我將數據直接放入列中。

   //Open and read the file 
       System.IO.FileStream fs = new System.IO.FileStream("myfilename", System.IO.FileMode.Open); 
       System.IO.StreamReader sr = new System.IO.StreamReader(fs); 

       string line = ""; 
       line = sr.ReadLine(); 

       string[] colVal; 

       try 
       { 
        //clear of previous data 
        //myDataTable.Clear(); 

        //for each reccord insert it into a row 
        while (!sr.EndOfStream) 
        { 
         line = sr.ReadLine(); 

          colVal = line.Split('\t'); 

          DataRow dataRow = myDataTable.NewRow(); 

          //associate values with the columns 
          dataRow["col1"] = colVal[0];   
          dataRow["col2"] = colVal[1]; 
          dataRow["col3"] = colVal[2]; 

          //add the row to the table 
          myDataTable.Rows.Add(dataRow); 
        } 

        //close the stream 
        sr.Close(); 

        //binds the dataset tothe grid view. 
        BindingSource bs = new BindingSource(); 
        bs.DataSource = myDataSet; 
        bs.DataMember = myDataTable.TableName; 
        myGridView.DataSource = bs; 
       } 

如果你有很多並且它們被編號,你可以修改它來爲列做一些循環。此外,我建議先檢查完整性,方法是檢查讀取的列數是否正確。